c# - "Property set method not found"反射时出错

标签 c# .net reflection

我正在尝试反射(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.SetPropertyBindingFlags.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/

相关文章:

c# - 从 Span<byte> 获取 Int32

.net - 这是哪种 .NET 查询语言?

c# - 如何在 C# 中确定数字类型是有符号还是无符号

c# - 类作为具有反射 C# 的另一个类的属性

c# - 检查 session 是否为空

c# - 安装计时器作业时出现意外异常 - 无法从程序集创建接收器对象

c# - 永远增加你得到-2147483648?

c# - HttpContext 和 HttpRequest 之间的区别?

c# - 如何在 .NET 中创建 shell 样式的标题栏按钮

java - 如何 "slice"一个POJO