代码之家  ›  专栏  ›  技术社区  ›  Programmin Tool

C:typescriptor.getAttributes()和getType().getCustomAttributes有什么区别?

  •  13
  • Programmin Tool  · 技术社区  · 15 年前

    以下两个代码:

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

    在哪里? RequiredIfOtherPropertyIsNotEmpty 是一个 ValidationAttribute 并且有 AllowMultiple = true .

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

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

    1 回复  |  直到 15 年前
        1
  •  9
  •   Tim Robinson    15 年前

    the MSDN page on TypeDescriptor.GetAttributes :

    为了返回 AttributeUsageAttribute.AllowMultiple 属性来自 AttributeCollection ,您的属性必须重写 Attribute.TypeId 属性。

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

    如果不需要这种运行时扩展,那么 类型描述符 处理多个属性是一个问题,您可能更擅长 Type.GetCustomAttributes .