4

このC#クラスがあるとします

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

ここで、リフレクションを使用してこのクラスを発見し、フィールドを見ていると、そのうちの 1 つが Array 型 (つまり、b) であることがわかりました。

foreach( FieldInfo fieldinfo in classType.GetFields() )
{
    if( fieldInfo.FieldType.IsArray )
    {
        int arraySize = ?;
        ...
    }
}

配列に配列を作成するフィールド初期化子があることは保証されていませんが、もしそうなら、フィールド初期化子によって作成された配列のサイズを知りたいです。

フィールド初期化子を呼び出す方法はありますか?

もしあれば、私は次のようなことをします:

Array initValue = call field initializer() as Array;
int arraySize = initValue.Length;

私が見つけたのは、クラス全体のインスタンスを作成することだけでしたが、やり過ぎなので、このようにしたくありません...

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 に答える