C#:FieldInfo.GetValue返回null

时间:2011-01-04 16:46:31

标签: c# reflection

我有一个问题是通过Reflection:

在变量o中检索我的控件f2
public partial class Form1 : Form
{
    private Form2 f2;

    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.Show();
    }

    private void button2_Click(object sender, EventArgs e)
    {
        Type controlType = this.GetType();
        FieldInfo f = controlType.GetField("f2", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
        object o = f.GetValue(this); // o == null;
    }
}

3 个答案:

答案 0 :(得分:9)

那是因为您在f2中创建了一个名为button1_Click的局部变量,但从未将类成员f2设置为该新实例:

private void button1_Click(object sender, EventArgs e)
{
    // Creates a new variable called f2 that is local to the function
    Form2 f2 = new Form2();

    // To store the local instance to the class member, you need to un-comment
    // this.f2 = f2;        
    // or change the previous line of code to:
    // f2 = new Form2();

    // Show the local form
    f2.Show();
}

因此,类级f2中存在空值。

我也假设你在这个例子中只是玩反射。如果这不是严格的反思测试......你应该直接引用this.f2而不是通过反思。

答案 1 :(得分:1)

FieldInfo myf = typeof(Form1).GetField("f2");
   Console.Writeline(myf.GetValue(this));

应该适用于你!

答案 2 :(得分:0)

您没有设置私有字段f2的值。相反,您正在创建一个名为f2的局部变量。而不是这段代码:

Form f2 = new Form();

使用:

f2 = new Form();