inheritance - C#, reflection, inheritence and static fields? -


i have family of classes inherit abstract superclass, implemented 2 concrete classes:

public abstract class abstractfoo  {     protected static string fooname = "reset me!";      public static string getname()     {          return fooname;     } } 

the subclasses constructed like

public class barfoo : abstractfoo  {     static barfoo()      {          fooname = "pretty name barfoo";     } } 

and forth.

i want list of abstractfoo implementations' pretty names user can decide implementation use.

my reflection code looks like

 type footype = typeof(abstractfoo);   list<assembly> assemblies = new list<assembly>(appdomain.currentdomain.getassemblies());   ienumerable<type> alltypes = assemblies.selectmany<assembly, type>(s => s.gettypes());  ienumerable<type> footypes = alltypes.where(p => p.issubclassof (footype));   foreach (type thistype in footypes)   {       methodinfo method = thistype.getmethod ("getname", bindingflags.public | bindingflags.static | bindingflags.flattenhierarchy);       string name = (string) method.invoke (null, null);   // add list, anyhow names.add (name);     } 

i end method.invoke returning "rename me" rather individual names.

i'm pretty sure i'm doing silly here, i'm not quite sure what.

you have 2 problems.

first, static field isn't going doing want to. there's one static field, in abstractfoo - there isn't separate barfoo.fooname static field. if have bunch of subclasses, whichever subclass gets type-initialized last "win" in setting field.

next, when invoke barfoo.getname, that's really call abstractfoo.getname - barfoo won't initialized, won't see "pretty name" being set.

fundamentally, suggest redesign code. recommend decorate each class attribute. way won't end relying on type initializer @ all, , don't need declare separate static member each type. downside value has constant...

an alternative use virtual property overridden in subclasses - although requires create instance of each type, of course.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -