“找不到属性设置方法”;反射时的错误 [英] "Property set method not found" error during reflection

查看:612
本文介绍了“找不到属性设置方法”;反射时的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to reflect over some class properties and set them programaticlly, but it looks like one of my PropertyInfo filters isn't working:

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

Because the property has only a get{} method, no set{} method.

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

My question is, why wasn't this property filtered out of props? I thought that was the purpose of BindingFlags.SetProperty.

该属性未被过滤掉是:

    public String CollTypeDescription
    {
        get { return _CollTypeDescription; }
    }

请注意,我想过滤不会提前使用的属性,因为我要一次列出所有这些信息。我要在事实确定我是否可以使用二传手之后使用 pi.GetSetMethod()

Note that I want to filter properties that won't work ahead of time, because I'm listing them all at once. I do not want to use pi.GetSetMethod() after the fact to determine whether I can use the setter.

推荐答案

从文档中


BindingFlags.SetProperty

BindingFlags.SetProperty

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

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的属性。

BindingFlags.SetProperty and BindingFlags.GetProperty do not filter properties that are missing setters or getters, respectively.

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

To check if a property can be set, use the CanWrite property.

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

这篇关于“找不到属性设置方法”;反射时的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆