How do you get the Value of a property from PropertyInfo?

后端 未结 4 1204
野性不改
野性不改 2020-12-16 09:58

I\'ve got an object that has a collection of properties. When I get the specific entity I can see the field I\'m looking for (opportunityid) and that it\'s

相关标签:
4条回答
  • 2020-12-16 10:15

    Use PropertyInfo.GetValue(). Assuming your property has the type Guid? then this should work:

    attrGuid = ((System.Guid?)info.GetValue(attr, null)).Value;
    

    Note that an exception will be thrown if the property value is null.

    0 讨论(0)
  • 2020-12-16 10:20

    If the name of the property is changing, you should use GetValue:

    info.GetValue(attr, null);
    

    The last attribute of that method can be null, since it is the index value, and that is only needed when accessing arrays, like Value[1,2].

    If you know the name of the attribute on beforehand, you could use the dynamic behavior of it: you can call the property without the need of doing reflection yourself:

    var x = attr.Guid;
    
    0 讨论(0)
  • 2020-12-16 10:22

    Unless the property is static, it is not enough to get a PropertyInfo object to get a value of a property. When you write "plain" C# and you need to get a value of some property, say, MyProperty, you write this:

    var val = obj.MyProperty;
    

    You supply two things - the property name (i.e. what to get) and the object (i.e. from where to get it).

    PropertyInfo represents the "what". You need to specify "from where" separately. When you call

    var val = info.GetValue(obj);
    

    you pass the "from where" to the PropertyInfo, letting it extract the value of the property from the object for you.

    Note: prior to .NET 4.5 you need to pass null as a second argument:

    var val = info.GetValue(obj, null);
    
    0 讨论(0)
  • 2020-12-16 10:36

    try with:

    attrGuid = (Guid)info.GetValue(attr,null)
    
    0 讨论(0)
提交回复
热议问题