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

Pro*_*ool 13 c# attributes typedescriptor

拿这两个代码:

instance.GetType()
 .GetCustomAttributes(true)
 .Where(item => item is ValidationAttribute);
Run Code Online (Sandbox Code Playgroud)

TypeDescriptor.GetAttributes(instance)
 .OfType<ValidationAttribute>();
Run Code Online (Sandbox Code Playgroud)

如果这个类看起来像:

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

RequiredIfOtherPropertyIsNotEmptya ValidationAttribute和a 在哪里AllowMultiple = true.

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

导致这种情况的区别是什么?

Tim*_*son 10

TypeDescriptor.GetAttributes上的MSDN页面:

AttributeUsageAttribute.AllowMultiple要从中返回属性的多个实例AttributeCollection,您的属性必须覆盖该Attribute.TypeId属性.

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

如果您不需要这种运行时扩展,并且TypeDescriptor处理多个属性的方式是一个问题,那么您可能会更好Type.GetCustomAttributes.