How do I get the value of MemberInfo?

后端 未结 3 720
感情败类
感情败类 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条回答
  •  梦毁少年i
    2021-02-11 15:20

    Jon's answer is ideal - just one observation: as part of general design, I would:

    1. generally avoid reflecting against non-public members
    2. avoid having public fields (almost always)

    The upshot of these two is that generally you only need to reflect against public properties (you shouldn't be calling methods unless you know what they do; property getters are expected to be idempotent [lazy loading aside]). So for a PropertyInfo this is just prop.GetValue(obj, null);.

    Actually, I'm a big fan of System.ComponentModel, so I would be tempted to use:

        foreach(PropertyDescriptor prop in TypeDescriptor.GetProperties(obj))
        {
            Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
        }
    

    or for a specific property:

        PropertyDescriptor prop = TypeDescriptor.GetProperties(obj)["SomeProperty"];
        Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(obj));
    

    One advantage of System.ComponentModel is that it will work with abstracted data models, such as how a DataView exposes columns as virtual properties; there are other tricks too (like performance tricks).

提交回复
热议问题