Can I make an array of classes in C#? (I don't want an array of objects) -
i have tried create array of classes, first of regular classes, of static classes, in both cases, hasn't worked. hasn't compiled.
class program { static class : bunch1 { } static class b : bunch1 { } class aa : bunch2 { } class bb : bunch2 { } class bunch1 { } class bunch2 { } static void main(string[] args) { bunch1[] bunch1s = new bunch1[] { a,b }; bunch2[] bunch2s = new bunch2[] { aa,bb }; } }
the compilation error has been aa "is 'type' used 'variable'" (same error message class - or b or aa or bb)
i can see (at least non static classes), can
bunch2[] bunch2s = new bunch2[] { new aa(),new bb() };
but don't want instances of classes.
i don't want array of objects.
added
a practical scenario of why.
i have bunch of classes each static field (public static char c), , i'd set field.
class { public static char c; } class b { public static char c; }
....
i say
a.c='x'; b.c='p'; c.c='w'; d.c='v';
but i'd rather say
char[] mychars= new char[] {'x','p','w','v'}; // create bunchofclasses array or list consisting of classes a,b,c,d (how, don't know). for(int i=0; i<5;i++) bunchofclasses[i].c= mychars[i];
unfortunately, can't have static contract/constraint classes have been grouped static members generalize them , access static members abstractly. have been put language, wasn't.
nevertheless, can still similar reflection, won't anywhere near tidy aiming for.
class { public static char c; } class b { public static char c; } class c { public static char c; } class d { public static char c; } var mychars = new char[] { 'a','b','c','d' }; var types = new[] { typeof(a), typeof(b), typeof(c), typeof(d) }; (int = 0; < types.length; i++) { var type = types[i]; var field = type.getfield("c", bindingflags.public | bindingflags.static); if (field == null) throw new invalidoperationexception("no such field."); // pass null instance static members, since there's no instance field.setvalue(null, mychars[i]); }
note in example, c
field. you'd need use different method (getproperty
, getmethod
) different kind of member.
Comments
Post a Comment