简体   繁体   中英

C#: What's the Difference Between TypeDescriptor.GetAttributes() and GetType() .GetCustomAttributes?

Take these two code things:

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

And

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

If the class looks like:

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

Where RequiredIfOtherPropertyIsNotEmpty is a ValidationAttribute and has AllowMultiple = true .

The first one returns two attributes, the second returns one.

What's the difference that would cause this?

From the MSDN page on TypeDescriptor.GetAttributes :

In order to return multiple instances of an AttributeUsageAttribute.AllowMultiple attribute from the AttributeCollection , your attribute must override the Attribute.TypeId property.

To answer the general question "what's the difference?": the values returned by TypeDescriptor can be extended at runtime, whereas those in Type cannot. The MSDN page I linked to explains more.

If you don't need this kind of runtime extension, and the way TypeDescriptor handles multiple attributes is a problem, you're probably better off with Type.GetCustomAttributes .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM