C#如何使用反射调用一个字段初始值? [英] C# how to invoke a field initializer using reflection?
问题描述
说我有这个C#类
public class MyClass {
int a;
int[] b = new int[6];
}
现在说我使用反射发现这个类在注视领域,我觉得其中一人是数组类型(如:b)
Now say I discover this class using reflection and while looking at the fields I find that one of them is of type Array (ie: b)
foreach( FieldInfo fieldinfo in classType.GetFields() )
{
if( fieldInfo.FieldType.IsArray )
{
int arraySize = ?;
...
}
}
我知道这不是保证阵列具有创建该数组,但如果它,我想知道由场初始创建的阵列的大小的字段初始化
I know it's not guaranteed that the array has a field initializer that creates the array but if it does 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 there was I would do something like this:
Array initValue = call field initializer() as Array;
int arraySize = initValue.Length;
唯一被我发现是创建整个类的实例,但我宁愿不这样做像这样的,因为它是矫枉过正...
The only was I found is to create an instance of the whole class but I would rather not do it like this as it's overkill...
推荐答案
好了,你不能。
下面的代码:
public class Test
{
public int[] test = new int[5];
public Test()
{
Console.Read();
}
}
将被编译为:
will be compiled 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 create an instance of the type, there is no way to know about the array size.
这篇关于C#如何使用反射调用一个字段初始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!