我正在尝试反射(reflect)一些类属性并以编程方式设置它们,但看起来我的 PropertyInfo 过滤器之一不起作用:
//Get all public or private non-static properties declared in this class (no inherited properties) - that have a getter and setter.
PropertyInfo[] props = this.GetType().GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.SetProperty );
我在网上收到一个错误
pi.SetValue(this, valueFromData, null);
因为该属性只有一个get{}
方法,没有set{}
方法。
我的问题是,为什么这个属性没有从 props 中过滤掉?我认为这就是 BindingFlags.SetProperty 的目的。
没有被过滤掉的属性是:
public String CollTypeDescription
{
get { return _CollTypeDescription; }
}
请注意,我想提前过滤掉无法使用的属性,因为我一次列出了它们。我不想在事后使用 pi.GetSetMethod()
来确定我是否可以使用 setter 。
最佳答案
来自文档:
BindingFlags.SetProperty
Specifies that the value of the specified property should be set. For COM properties, specifying this binding flag is equivalent to specifying PutDispProperty and PutRefDispProperty.
BindingFlags.SetProperty
和 BindingFlags.GetProperty
不分别过滤缺少 setter 或 getter 的属性。
要检查是否可以设置属性,请使用 CanWrite
属性。
if (pi.CanWrite)
pi.SetValue(this, valueFromData, null);
关于c# - "Property set method not found"反射时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9364092/