2009-12-02 53 views
12

取这两个代码件事:C#:TypeDescriptor.GetAttributes()和GetType().GetCustomAttributes之间的区别是什么?

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 
{ 
    ... 
} 

RequiredIfOtherPropertyIsNotEmptyValidationAttribute并具有AllowMultiple = true

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

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

+0

另请参见[typedescriptor-getproperties-vs -type-getproperties](http://stackoverflow.com/questions/1402239/typedescriptor-getproperties-vs-type-getproperties) – nawfal 2014-07-20 06:39:52

回答

9

the MSDN page on TypeDescriptor.GetAttributes

为了从AttributeCollection返回​​属性的多个实例,您的属性必须重写Attribute.TypeId财产。

要回答的一般问题“有什么区别?”:由TypeDescriptor返回的值可以在运行时扩展,而那些在Type不能。我链接到的MSDN页面解释更多。

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

+1

因此Type.GetCustomAttributes无法获取添加的属性在运行时(我的意思是使用TypeDescriptor.AddAttributes(...)添加的属性)对吗? – Gintama 2015-06-16 08:17:04

+0

'TypeDescriptor.GetAttributes(...)'至少不可用'netstandard1.3'和'netstandard1.4' – manuc66 2018-01-27 13:44:49

相关问题