C # how to call a field initializer using reflection?
Let's say I have this C # class
public class MyClass {
int a;
int[] b = new int[6];
}
Now tell me that I'm opening this class using reflection and looking at the fields I found that one of them is of type Array (i.e .: b)
foreach( FieldInfo fieldinfo in classType.GetFields() )
{
if( fieldInfo.FieldType.IsArray )
{
int arraySize = ?;
...
}
}
I know this does not guarantee that there is a field initializer in the array that creates the array, but if so, I would like to know the size of the array created by the field initializer.
Is there a way to call the field initializer?
If I were, I would do something like this:
Array initValue = call field initializer() as Array;
int arraySize = initValue.Length;
The only thing I found was to instantiate the whole class, but I would rather not do this in the way that it overflows ...
+3
source to share
2 answers
Well, you can't.
The following code:
public class Test
{
public int[] test = new int[5];
public Test()
{
Console.Read();
}
}
will compile as:
public class Program
{
public int[] test;
public Program()
{
// Fields initializers are inserted at the beginning
// of the class constructor
this.test = new int[5];
// Calling base constructor
base.ctor();
// Executing derived class constructor instructions
Console.Read();
}
}
So, until you instantiate the type, there is no way to know the size of the array.
+3
source to share