Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#:什么';TypeDescriptor.GetAttributes()和GetType().GetCustomAttributes之间的区别是什么?_C#_Attributes_Typedescriptor - Fatal编程技术网

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