繁体   English   中英

使用反射时如何理解myFieldInfo.GetValue(null)?

[英]How to understand myFieldInfo.GetValue(null) when using Reflection?

这是我关于反射的代码:

class Program
{
    private static int a = 100;

    static void Main(string[] args)
    {
        Console.WriteLine("a=" + a);

        Type t = typeof(Program);
        FieldInfo myFieldInfo = t.GetField("a",BindingFlags.NonPublic|BindingFlags.Static);
        if (myFieldInfo!=null)
        {
            Console.WriteLine("The current value of a is "+myFieldInfo.GetValue(null)+", please enter a new value:");
            string newValue = Console.ReadLine();
            int newInt;
            if (int.TryParse(newValue,out newInt))
            {
                myFieldInfo.SetValue(null, newInt);
                Console.WriteLine("a=" + a);
            }
        }

    }
}

它可以工作! 但我真的不理解的含义是nullmyFieldInfo.GetValue(null)myFieldInfo.SetValue(null, newInt); ,并且阅读了有关FieldInfo.GetValue方法(对象)的MSDN,我发现该Object意思是“将返回其字段值的对象。”。 因此,这真让我感到困惑,为什么参数应该为null

通常,您将在其中放置要从中获取字段值的实例。 由于在您的代码中该字段是静态的,因此它没有绑定到实例。 因此,instance参数可以(并且应该)为null。

因为它是静态的,所以来自MSDN

如果该字段是静态的,则obj被忽略。 对于非静态字段,obj应该是继承或声明该字段的类的实例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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