4

Say I have this C# class

public class MyClass {
    int a;
    int[] b = new int[6];
}

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...

4

2 回答 2

3

好吧,你不能。

以下代码:

public class Test
{
    public int[] test = new int[5];

    public Test()
    {
        Console.Read();
    }
}

将编译为:

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();
    }
}

因此,在您创建该类型的实例之前,无法知道数组的大小。

于 2013-02-06T15:57:19.727 回答
0

我认为您别无选择,只能创建该类的一个实例,因为在您这样做之前它不存在。

于 2013-02-06T15:46:56.440 回答