C#:FieldInfo.GetValue返回null

C#:FieldInfo.GetValue返回null,c#,reflection,C#,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();

我在通过反射检索变量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;
    }
}

这是因为您在
按钮1中创建了一个名为
f2
的局部变量,但从未将类成员
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中创建了一个名为
f2
的局部变量,但决不能将类成员
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,而不是通过反射。

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

Form f2 = new Form();
使用:


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

Form f2 = new Form();
使用:

应该为你工作


应该为你工作

我的问题是:为什么不直接访问值?我的问题是:为什么不直接访问值?