How do I get the value of MemberInfo?

后端 未结 3 714
感情败类
感情败类 2021-02-11 14:40

How do I get the value of a MemberInfo object? .Name returns the name of the variable, but I need the value.

I think you can do this with

3条回答
  •  死守一世寂寞
    2021-02-11 15:35

    Here's an example for fields, using FieldInfo.GetValue:

    using System;
    using System.Reflection;
    
    public class Test
    {
        // public just for the sake of a short example.
        public int x;
    
        static void Main()
        {
            FieldInfo field = typeof(Test).GetField("x");
            Test t = new Test();
            t.x = 10;
    
            Console.WriteLine(field.GetValue(t));
        }
    }
    

    Similar code will work for properties using PropertyInfo.GetValue() - although there you also need to pass the values for any parameters to the properties. (There won't be any for "normal" C# properties, but C# indexers count as properties too as far as the framework is concerned.) For methods, you'll need to call Invoke if you want to call the method and use the return value.

提交回复
热议问题