reflection过程中出现“找不到属性集方法”错误

我试图反映一些类属性并以编程方式设置它们,但看起来我的PropertyInfofilter之一无法正常工作:

//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{}方法。

我的问题是,为什么这个属性没有过滤掉道具? 我认为那是BindingFlags.SetProperty的目的。

未过滤掉的属性是:

  public String CollTypeDescription { get { return _CollTypeDescription; } } 

请注意,我想要过滤不会提前工作的属性,因为我会立即列出所有属性。 事实上我不想使用pi.GetSetMethod()来确定我是否可以使用setter。

从文档:

BindingFlags.SetProperty

指定应设置指定属性的值。 对于COM属性,指定此绑定标志等同于指定PutDispProperty和PutRefDispProperty。

BindingFlags.SetPropertyBindingFlags.GetProperty 不会分别过滤缺少setter或getter的属性。

要检查是否可以设置属性,请使用CanWrite属性。

 if (pi.CanWrite) pi.SetValue(this, valueFromData, null); 

感谢ken的信息。 它似乎是我可以通过在LINQfilter中测试GetSetMethod(true)来过滤它们的最佳解决方案:

 //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).Where(p => p.GetGetMethod(true) != null && p.GetSetMethod(true) != null).ToArray(); 

我理解GetProperties()方法,以便它返回具有BindingFlags.GetProperty BindingFlags.SetProperty每个属性。
因此,如果您只想要具有setter的属性,则必须删除BindingFlags.GetProperty标志。 但我没有测试它,所以我错了。

我的回答是-1。 所以我的答案似乎错了。