C#中:什么是TypeDescriptor.GetAttributes()和的GetType().GetCustomAttributes之间的区别?
-
11-09-2019 - |
题
取这两个代码的东西:
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
。
第一个返回两个属性,所述第二返回一个。
有什么会导致这种不同?
解决方案
从上TypeDescriptor.GetAttributes的MSDN页一>:
为了返回从
AttributeUsageAttribute.AllowMultiple
一个AttributeCollection
属性的多个实例,您的属性必须重写Attribute.TypeId
属性。
要回答的一般问题“有什么区别?”:由TypeDescriptor
返回的值可以在运行时扩展,而那些在Type
不能。我链接到MSDN页面详细解释了。
如果您不需要这种运行时扩展的,并且TypeDescriptor
的方式处理多个属性是一个问题,你可能有Type.GetCustomAttributes
更好。
不隶属于 StackOverflow