C#:什么';TypeDescriptor.GetAttributes()和GetType().GetCustomAttributes之间的区别是什么?
以这两个代码为例:C#:什么';TypeDescriptor.GetAttributes()和GetType().GetCustomAttributes之间的区别是什么?,c#,attributes,typedescriptor,C#,Attributes,Typedescriptor,以这两个代码为例: instance.GetType() .GetCustomAttributes(true) .Where(item => item is ValidationAttribute); 及 其中,requiredForotherPropertyIsnotempty是一个ValidationAttribute并且具有AllowMultiple=true 第一个返回两个属性,第二个返回一个 造成这种情况的原因是什么?来自: 为了从AttributeCollection返回
instance.GetType()
.GetCustomAttributes(true)
.Where(item => item is ValidationAttribute);
及
其中,requiredForotherPropertyIsnotempty
是一个ValidationAttribute
并且具有AllowMultiple=true
第一个返回两个属性,第二个返回一个
造成这种情况的原因是什么?来自:
为了从AttributeCollection
返回AttributeUsageAttribute.AllowMultiple
属性的多个实例,您的属性必须覆盖属性.TypeId
属性
回答一般问题“有什么区别?”:由TypeDescriptor
返回的值可以在运行时扩展,而Type
中的值不能扩展。我链接到的MSDN页面解释了更多内容
如果您不需要这种运行时扩展,并且
TypeDescriptor
处理多个属性的方式存在问题,那么最好使用Type.GetCustomAttributes
另请参见So Type.GetCustomAttributes无法获取在运行时添加的属性(我是指通过使用TypeDescriptor.AddAttributes(…)添加的属性,对吗?TypeDescriptor.GetAttributes(…)
不适用于至少netstandard1.3
和netstandard1.4
TypeDescriptor.GetAttributes(instance)
.OfType<ValidationAttribute>();
[RequiredIfOtherPropertyIsNotEmpty("State", "City", ErrorMessage = ErrorDescription.CreateAccount_CityRequiredWithState)]
[RequiredIfOtherPropertyIsNotEmpty("State", "Address1", ErrorMessage = ErrorDescription.CreateAccount_Address1RequiredWithState)]
public class ManagePostModel
{
...
}