2009-12-02 11 views
12

bu iki kod şeyleri atın:C#: TypeDescriptor.GetAttributes() ve GetType() .GetCustomAttributes Arasındaki Fark Nedir?

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

Ve

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

sınıf gibi görünüyorsa

:

RequiredIfOtherPropertyIsNotEmpty bir ValidationAttribute ve AllowMultiple = true sahiptir
[RequiredIfOtherPropertyIsNotEmpty("State", "City", ErrorMessage = ErrorDescription.CreateAccount_CityRequiredWithState)] 
[RequiredIfOtherPropertyIsNotEmpty("State", "Address1", ErrorMessage = ErrorDescription.CreateAccount_Address1RequiredWithState)] 
public class ManagePostModel 
{ 
    ... 
} 

.

Birincisi iki özniteliği, ikinci bir tane döndürür.

Buna neden olan fark nedir? the MSDN page on TypeDescriptor.GetAttributes itibaren

+0

da [TypeDescriptor-GetProperties-vs-tipi-GetProperties] Bkz (http://stackoverflow.com/questions/1402239/typedescriptor-getproperties-vs-type-getproperties) – nawfal

cevap

9

:

AttributeCollection bir AttributeUsageAttribute.AllowMultiple özelliğinin birden çok örneğini döndürmek için, sizin nitelik Attribute.TypeId özelliğini geçersiz kılmalıdır.

genel soruya cevap vermek için "fark nedir?": TypeDescriptor tarafından döndürülen değerler Type olamaz olanlar ise, çalışma zamanında uzatılabilir. Bağlandığım MSDN sayfası daha fazlasını açıklıyor.

Bu tür bir çalışma zamanı uzantısına ihtiyacınız yoksa ve TypeDescriptor'un birden çok özniteliği işleme biçimi sorunsa, muhtemelen Type.GetCustomAttributes ile daha iyisiniz.

+1

Yani Type.GetCustomAttributes eklenen özelliklerini alamayan Çalışma zamanında (ben TypeDescriptor.AddAttributes (...) kullanarak ekledi öznitelikler) doğru? – Gintama

+0

'TypeDescriptor.GetAttributes (...)', en azından 'netstandard1.3' ve' netstandard1.4' için mevcut değildir. – manuc66

İlgili konular