C#: TypeDescriptor.GetAttributes()和GetType().GetCustomAttributes()有什么区别?

13

请看这两段代码:

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
{
   ...
}

其中RequiredIfOtherPropertyIsNotEmpty是一个ValidationAttribute,并且具有AllowMultiple = true

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

这种差异的原因是什么?


1个回答

9
TypeDescriptor.GetAttributes 的 MSDN 页面
为了从 AttributeCollection 返回 AttributeUsageAttribute.AllowMultiple 属性的多个实例,您的属性必须覆盖 Attribute.TypeId 属性。
回答一般问题“有什么区别?”:TypeDescriptor 返回的值可以在运行时扩展,而 Type 中的值则不能。我链接的 MSDN 页面有更详细的解释。
如果您不需要这种运行时扩展,并且 TypeDescriptor 处理多个属性的方式是一个问题,那么您使用 Type.GetCustomAttributes 可能会更好。

1
那么Type.GetCustomAttributes无法获取在运行时添加的属性(我指使用TypeDescriptor.AddAttributes(...)添加的属性)是吗? - Gintama
1
TypeDescriptor.GetAttributes(...) is not not available for at least netstandard1.3 and netstandard1.4 - manuc66

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接