简体   繁体   中英

C# : FieldInfo.GetValue returns null

I've a problem to retrieve my control f2 in the variable o via Reflection :

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

That's because you create a local variable called f2 in button1_Click but never set the class member f2 to that new instance:

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

Therefore there is a null value in the class level f2 .

I'm also assuming that you're just playing with reflection in this example. If this isn't strictly a test of reflection...you should just reference this.f2 directly rather than through reflection.

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

Should work for ya!

You aren't setting the value of the private field f2. Instead you are creating a local variable called f2. Instead of this code:

Form f2 = new Form();

use:

f2 = new Form();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM