当type.GetProperties()时过滤掉受保护的setter

mci*_*321 5 c# reflection protected getproperties

我试图反映一种类型,并只获取具有公共设置器的属性。这似乎不适用于我。在下面的示例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;}
}
Run Code Online (Sandbox Code Playgroud)

Eli*_*sha 5

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

例如:

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

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

由于属性的可见性可能不同于设置器,因此需要通过设置器方法的可见性进行过滤。