C #: Qual è la differenza tra TypeDescriptor.GetAttributes () e getType) .GetCustomAttributes (?

StackOverflow https://stackoverflow.com/questions/1833288

  •  11-09-2019
  •  | 
  •  

Domanda

Prendere queste due cose codice:

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

E

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

Se la classe si presenta come:

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

Dove RequiredIfOtherPropertyIsNotEmpty è una ValidationAttribute e ha AllowMultiple = true.

Il primo restituisce due attributi, la seconda restituisce uno.

Qual è la differenza che potrebbe causare questo?

È stato utile?

Soluzione

pagina MSDN TypeDescriptor.GetAttributes :

  

Per tornare più istanze di un attributo AttributeUsageAttribute.AllowMultiple dal AttributeCollection, l'attributo deve sostituire la proprietà Attribute.TypeId.

Per rispondere alla domanda generale "che cosa è la differenza?": I valori restituiti dalla TypeDescriptor possono essere estesi in fase di esecuzione, mentre quelli in Type non può. La pagina di MSDN ho collegato al spiega di più.

Se non avete bisogno di questo tipo di estensione runtime, e il modo in cui TypeDescriptor gestisce più attributi è un problema, si è probabilmente meglio con Type.GetCustomAttributes.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top