GetCustomAttributes(true) 不从类型父级返回属性?

发布于 2024-12-14 13:44:50 字数 588 浏览 2 评论 0原文

我有以下(大大简化的)类:

public class Customer {
    [Required(ErrorMessageResourceName="Required", ErrorMessageResourceType=typeof(ResourcesCommon.ValidationStrings))]
    public string LastName { get; set; }
}

public class SalesCustomer : Customer {
    ...
}

我有一些循环遍历 SalesCustomer 属性的验证代码。每个属性都按以下方式进行评估:

 var validators = property.GetCustomAttributes(typeof(ValidationAttribute), true);

问题是,当我查看 SalesCustomer 类型的 LastName 属性时,未返回必需属性,但当我查看 Customer 类型时,它确实工作正常。这很令人困惑,因为 GetCustomerAttribute() 方法明确需要一个布尔值来指示将返回继承的属性。

I have the following (greatly simplified) classes:

public class Customer {
    [Required(ErrorMessageResourceName="Required", ErrorMessageResourceType=typeof(ResourcesCommon.ValidationStrings))]
    public string LastName { get; set; }
}

public class SalesCustomer : Customer {
    ...
}

I have some validation code that loops through SalesCustomer properties. Each property is evaluated with this:

 var validators = property.GetCustomAttributes(typeof(ValidationAttribute), true);

The problem is that the Required attribute is not getting returned when I look at the LastName property on the SalesCustomer type but it does work fine when I look at the Customer type. This is confusing since the GetCustomerAttribute() method explicitly wants a boolean indicating that the inherited attributes will be returned.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

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

评论(1

鸠书 2024-12-21 13:44:50

我相信它只会返回来自覆盖父成员的属性,而不是隐藏父成员的属性。

将基本属性设置为虚拟,并将子属性设置为覆盖

I believe that it will only return attributes from overridden parent members, not shadowed parent members.

Make the base property virtual and the child property overrrides.

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