属性名称并需要其值

Cop*_*ill 1 c# properties

我有一个属性的名称,需要在一个类中找到它的值,获得这个值的最快方法是什么?

Fre*_*örk 15

我假设你在运行时拥有属性的名称; 不是在编码时......

假设您的类名为TheClass,它有一个名为TheProperty的属性:

object GetThePropertyValue(object instance)
{
    Type type = instance.GetType();
    PropertyInfo propertyInfo = type.GetProperty("TheProperty");
    return propertyInfo.GetValue(instance, null);
}
Run Code Online (Sandbox Code Playgroud)

  • 你打败了我.注意,该函数不需要具有特定类型的参数.我相信`对象实例'会做得很好. (3认同)