【问题标题】:Filtering out protected setters when type.GetProperties()type.GetProperties() 时过滤掉受保护的设置器
【发布时间】:2011-11-25 09:40:33
【问题描述】:

我试图反映一个类型,并且只获取具有公共设置器的属性。这似乎对我不起作用。在下面的示例 LinqPad 脚本中,“Id”和“InternalId”与“Hello”一起返回。我该怎么做才能过滤掉它们?

void Main()
{
    typeof(X).GetProperties(BindingFlags.SetProperty | BindingFlags.Public | BindingFlags.Instance)
    .Select (x => x.Name).Dump();
}

public class X
{
    public virtual int Id { get; protected set;}
    public virtual int InternalId { get; protected internal set;}
    public virtual string Hello { get; set;}
}

【问题讨论】:

    标签: c# reflection protected getproperties


    【解决方案1】:

    您可以使用GetSetMethod() 来确定setter 是否公开。

    例如:

    typeof(X).GetProperties(BindingFlags.SetProperty |
                            BindingFlags.Public |
                            BindingFlags.Instance)
        .Where(prop => prop.GetSetMethod() != null)
        .Select (x => x.Name).Dump();
    

    GetSetMethod() 返回方法的公共 setter,如果没有则返回 null

    由于属性可能具有与 setter 不同的可见性,因此需要按 setter 方法的可见性进行过滤。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-19
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 2014-03-05
      • 2012-02-12
      相关资源
      最近更新 更多