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

发布于 2024-12-06 17:30:07 字数 463 浏览 0 评论 0原文

我试图反映一种类型,并仅获取具有公共设置器的属性。这似乎对我不起作用。在下面的示例 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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

海风掠过北极光 2024-12-13 17:30:07

您可以使用 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 方法可见性进行过滤。

You can use the GetSetMethod() to determine whether the setter is public or not.

For example:

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

The GetSetMethod() returns the public setter of the method, if it doesn't have one it returns null.

Since the property may have different visibility than the setter it is required to filter by the setter method visibility.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文