当 type.GetProperties() 时过滤掉受保护的 setter
我试图反映一种类型,并仅获取具有公共设置器的属性。这似乎对我不起作用。在下面的示例 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;}
}
I am trying to reflect over a type, and get only the properties with public setters. This doesn't seem to be working for me. In the example LinqPad script below, 'Id' and 'InternalId' are returned along with 'Hello'. What can I do to filter them out?
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;}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 GetSetMethod() 来确定 setter 是否是公共的或不。
例如:
GetSetMethod()
返回方法的公共 setter,如果没有,则返回null
。由于属性可能具有与 setter 不同的可见性,因此需要通过 setter 方法可见性进行过滤。
You can use the GetSetMethod() to determine whether the setter is public or not.
For example:
The
GetSetMethod()
returns the public setter of the method, if it doesn't have one it returnsnull
.Since the property may have different visibility than the setter it is required to filter by the setter method visibility.