【问题标题】:C#: What's the Difference Between TypeDescriptor.GetAttributes() and GetType() .GetCustomAttributes?C#:TypeDescriptor.GetAttributes() 和 GetType() .GetCustomAttributes 有什么区别?
【发布时间】:2009-12-02 14:37:53
【问题描述】:

拿这两个代码的东西:

instance.GetType()
 .GetCustomAttributes(true)
 .Where(item => item is ValidationAttribute);

TypeDescriptor.GetAttributes(instance)
 .OfType<ValidationAttribute>();

如果类看起来像:

[RequiredIfOtherPropertyIsNotEmpty("State", "City", ErrorMessage = ErrorDescription.CreateAccount_CityRequiredWithState)]
[RequiredIfOtherPropertyIsNotEmpty("State", "Address1", ErrorMessage = ErrorDescription.CreateAccount_Address1RequiredWithState)]
public class ManagePostModel
{
   ...
}

其中RequiredIfOtherPropertyIsNotEmptyValidationAttribute 并具有AllowMultiple = true

第一个返回两个属性,第二个返回一个。

有什么不同会导致这种情况?

【问题讨论】:

标签: c# attributes typedescriptor


【解决方案1】:

来自the MSDN page on TypeDescriptor.GetAttributes

为了从AttributeCollection 返回AttributeUsageAttribute.AllowMultiple 属性的多个实例,您的属性必须覆盖Attribute.TypeId 属性。

回答一般问题“有什么区别?”:TypeDescriptor 返回的值可以在运行时扩展,而Type 中的值不能。我链接到的 MSDN 页面解释了更多。

如果您不需要这种运行时扩展,并且TypeDescriptor 处理多个属性的方式存在问题,那么您最好使用Type.GetCustomAttributes

【讨论】:

  • 所以 Type.GetCustomAttributes 无法获取在运行时添加的属性(我的意思是使用 TypeDescriptor.AddAttributes(...) 添加的属性)对吗?
  • TypeDescriptor.GetAttributes(...) 至少不适用于netstandard1.3netstandard1.4
猜你喜欢
  • 2015-01-12
  • 1970-01-01
  • 2011-05-31
  • 2011-04-05
  • 1970-01-01
  • 2011-02-13
  • 1970-01-01
  • 1970-01-01
  • 2021-08-31
相关资源
最近更新 更多