使用反射,我如何检测具有setter的属性.

leo*_*ora 43 c# reflection

我有这个代码循环一个对象,并通过反射获取其所有属性:

foreach (var propertyInfo in typeof(TBase).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
    var oldValue = propertyInfo.GetValue(oldVersion, null);
}
Run Code Online (Sandbox Code Playgroud)

如何检查只查看其上有"设置"的属性?(我想忽略只读值 - 只是"获取".)

STO*_*STO 103

PropertyInfo.CanWrite(文件)

要么

PropertyInfo.GetSetMethod(文件)

  • 我建议使用PropertyInfo.GetSetMethod并检查它是否为null; 如果属性上有私有,受保护或内部集,则PropertyInfo.CanWrite方法将返回true.如果属性上实际上没有setter,它将只返回false. (19认同)
  • 这肯定会奏效,但您必须对每个属性进行额外检查。通过设置 BindingFlags.SetProperty,您将只检索包含 setter 的属性。 (2认同)

Kir*_*oll 15

propertyInfo.GetSetMethod() != null
Run Code Online (Sandbox Code Playgroud)