如果我在运行时不知道属性名称,如何返回属性的值?

HCP*_*HCP 0 c# reflection

为简单起见,我们假设属性的值需要始终作为字符串返回.

public string GetTheValueOfTheProperty(PropertyInfo propertyInfo,Object myObject){
       string propname = propertyInfo.Name;
       if (propName == "IsSelected"){
          return myObject.IsSelected.ToString();
       }
    //...
}
Run Code Online (Sandbox Code Playgroud)

这有效,但如果我不知道属性的名称,它就不起作用.在那种情况下我该怎么做?

Kie*_*one 5

http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue.aspx

你可以打电话propertyInfo.GetValue(myObject, null);.

你可以转换为stringwith ToString(),但你应该null首先检查值 - 否则你会得到一个NullReferenceException.