C# how to invoke a field initializer using reflection?

孤者浪人 提交于 2019-12-23 16:33:40

问题


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


回答1:


Well, you can't.

The following code:

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.




回答2:


I dont think you have an option but to create an instance of the class as it doesnt exist until you do that.



来源:https://stackoverflow.com/questions/14732926/c-sharp-how-to-invoke-a-field-initializer-using-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!