反射过程中出现"找不到属性集方法"错误

Ala*_*ain 30 .net c# reflection

我试图反映一些类属性并以编程方式设置它们,但看起来我的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 );
Run Code Online (Sandbox Code Playgroud)

我收到了错误

pi.SetValue(this, valueFromData, null);
Run Code Online (Sandbox Code Playgroud)

因为该属性只有一个get{}方法,没有set{}方法.

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

未过滤掉的属性是:

    public String CollTypeDescription
    {
        get { return _CollTypeDescription; }
    }
Run Code Online (Sandbox Code Playgroud)

请注意,我希望过滤不会提前工作的属性,因为我会立即列出所有属性.我希望使用pi.GetSetMethod()的事实后,以确定自己是否可以使用二传手.

ken*_*ken 66

从文档:

BindingFlags.SetProperty

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

BindingFlags.SetProperty并且BindingFlags.GetProperty 不要分别过滤缺少setter或getter的属性.

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

if (pi.CanWrite)
    pi.SetValue(this, valueFromData, null);
Run Code Online (Sandbox Code Playgroud)


Ala*_*ain 7

感谢肯提供信息。它看起来是最好的解决方案,我可以通过在 LINQ 过滤器中测试 GetSetMethod(true) 来过滤掉它们:

// Get all public or private non-static properties declared in this class
// (e.g. excluding 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();
Run Code Online (Sandbox Code Playgroud)

或者,使用CanReadCanWrite

PropertyInfo[] props = this.GetType()
    .GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance |
                   BindingFlags.Public | BindingFlags.NonPublic)
    .Where(p => p.CanRead && p.CanWrite)
    .ToArray();
Run Code Online (Sandbox Code Playgroud)

我不清楚这些不同的方法是否会对获取/设置方法的不同保护级别产生不同的结果。