Property Name and need its value

后端 未结 5 980
萌比男神i
萌比男神i 2020-12-17 06:42

I have a name of a property and need to find its value within a Class, what is the fastest way of getting to this value?

相关标签:
5条回答
  • 2020-12-17 07:29

    I assume you mean you have the name of the property as a string. In this case, you need to use a bit of reflection to fetch the property value. In the example below the object containing the property is called obj.

    var prop = obj.GetType().GetProperty("PropertyName");
    var propValue = prop.GetValue(obj, null);
    

    Hope that helps.

    0 讨论(0)
  • 2020-12-17 07:36

    I am making the assumption that you have the name of the property in runtime; not while coding...

    Let's assume your class is called TheClass and it has a property called TheProperty:

    object GetThePropertyValue(object instance)
    {
        Type type = instance.GetType();
        PropertyInfo propertyInfo = type.GetProperty("TheProperty");
        return propertyInfo.GetValue(instance, null);
    }
    
    0 讨论(0)
  • 2020-12-17 07:39

    If you're interested in speed at runtime rather than development, have a look at Jon Skeet's Making reflection fly and exploring delegates blog post.

    0 讨论(0)
  • 2020-12-17 07:40

    Just use the name of the property. If it is a nullable property (e.g. int ? property) use property.Value.

    0 讨论(0)
  • 2020-12-17 07:46

    At runtime you can use reflection to get the value of the property.

    Two caveats:

    • Obfuscation: An obfuscator may change the name of the property, which will break this functionality.

    • Refactoring: Using reflection in this manner makes the code more difficult to refactor. If you change the name of the property, you may have to search for instances where you use reflection to get the property value based upon name.

    0 讨论(0)
提交回复
热议问题