Thursday 15 July 2010

java - C# Getting a list of classes that extend a base class -



java - C# Getting a list of classes that extend a base class -

thanks morgano first part of problem solved..

alright, can in java, i'm having problems doing c#..

here's base of operations class (stripped):

public abstract class packet { }

here's illustration of derived classes ( have quite few of them ):

public class foo : packet { public override void decode(datainputstream input) { throw new notimplementedexception(); } }

after browsing stack overflow , other websites awhile, found solution, either doesn't work or i'm doing wrong.

public static list<t> getinstances<t>() { homecoming (from t in assembly.getexecutingassembly().gettypes() t.getinterfaces().contains(typeof(t)) && t.getconstructor(type.emptytypes) != null select (t)activator.createinstance(t)).tolist(); }

which i'm calling this:

console.writeline(packetdecoder.getinstances<packet>().count + "");

and count returns 0, displays there aren't classes.

note: writing of library, phone call getinstaces in project, thought , moved packet classes on executable project as-well , didn't have effect.

your question still not quite clear. title says want find specific types inherit (the c# equivalent of "extends") base of operations type, code posted creates instances of types. or, @ to the lowest degree if correct.

the biggest issue calling getinterfaces(), don't seem dealing interfaces. instead, seek code:

static list<t> getinstances<t>() { homecoming assembly.getexecutingassembly() .gettypes().where(type => typeof(t).isassignablefrom(type) && type.getconstructor(type.emptytypes) != null) .select(type => (t)activator.createinstance(type)) .tolist(); }

note utilize of isassignablefrom() instead.

something else careful assembly inspecting. it's not clear post assembly right 1 in, assembly class has few different getxxxassembly() methods, each of different things. "executing" assembly not same "calling" assembly not same "entry" assembly, of of course of study not same assembly identified type declared in assembly.

finally note above homecoming base of operations class, if it's in same assembly you're inspecting. may or may not want, assume can figure out on own how deal if it's not. :)

java c# class interface annotations

No comments:

Post a Comment