如何判断一个类属性是否具有公共设置(.NET)?

6

我有这个:

public string Log
        {
            get { return log; }
            protected set
            {
                if (log != value)
                {
                    MarkModified(PropertyNames.Log, log);
                    log = value;
                }
            }

        }

我的数据绑定实用类能够做到这一点:

PropertyInfo pi = ReflectionHelper.GetPropertyInfo(boundObjectType, sourceProperty);

if (!pi.CanWrite)
                SetReadOnlyCharacteristics(boundEditor);

但 PropertyInfo.CanWrite 并不关心 set 是否公开访问,只关心它是否存在。

我该如何确定是否存在 公开 的 set,而不仅仅是 任何 set 呢?

5个回答

2
你需要使用BindingFlags。类似这样的方式。
PropertyInfo property = type.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);

1

在 PropertyInfo 上调用 GetSetMethod,获取 MethodInfo 并检查其属性,如 IsPublic。


1

与其他答案中建议更改 ReflectionHelper 的方法不同,另一种方法是调用 pi.GetSetMethod(false) 然后查看结果是否为 null。


0
在 ReflectionHelper.GetPropertyInfo() 方法中,你可能会调用 boundObjectType.GetType().GetProperties() 方法,其中 BindingFlags 参数显然包括 BindingFlags.NonPublic。你需要指定只有 BindingFlags.Public。

这样是行不通的,属性可以是公共的,而它的 "set" 可以是私有的或者内部的。 - Ilya Ryzhenkov

0

很难确定,因为你有一个“ReflectionHelper”类,我们无法看到源码。但是,我的第一个猜测是当你调用Type.GetProperty时没有正确设置BindingFlags属性。你需要OR公共枚举标志,以确保只返回公共值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接