c# - GetConstructors doesn't find the declared constructor -


i'm experimenting system.type. in following code, used getconstructors on array type:

using system; using system.reflection;  class animal  {     public animal (string s)     {         console.writeline(s);     } }  class test {     public static void main()     {         type animalarraytype = typeof(animal).makearraytype();         console.writeline(animalarraytype.getconstructors()[0]);     } } 

the output is: void .ctor(int32). why? shouldn't void .ctor(system.string)?

you called .makearraytype() you're doing reflection on array of animal, not animal itself. if remove that, you'll constructor expected.

type animalarraytype = typeof(animal); console.writeline(animalarraytype.getconstructors()[0]); 

if wanted element type of array type, can this.

type animalarraytype = typeof(animal[]); console.writeline(animalarraytype.getelementtype().getconstructors()[0]); 

in order construct array of desired size, can use this.

type animalarraytype = typeof(animal[]); var ctor = animalarraytype.getconstructor(new[] { typeof(int) }); object[] parameters = { 3 }; var animals = (animal[])ctor.invoke(parameters); 

Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -