C#: typedescriptor.getAttributes ()와 getType () .getCustomAttributes의 차이점은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/1833288

  •  11-09-2019
  •  | 
  •  

문제

이 두 코드를 가져 가십시오.

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 a ValidationAttribute 그리고 있습니다 AllowMultiple = true.

첫 번째는 두 가지 속성을 반환하고 두 번째 속성은 하나를 반환합니다.

이것을 일으키는 차이점은 무엇입니까?

도움이 되었습니까?

해결책

에서 typedescriptor.getAttributes의 MSDN 페이지:

여러 인스턴스를 반환하기 위해 AttributeUsageAttribute.AllowMultiple .의 속성 AttributeCollection, 당신의 속성은 Attribute.TypeId 재산.

일반적인 질문에 대답하려면 "차이점은 무엇입니까?": 반환 된 값 TypeDescriptor 런타임에 연장 할 수있는 반면 Type 할 수 없습니다. MSDN 페이지가 더 설명합니다.

이런 종류의 런타임 확장이 필요하지 않은 경우 TypeDescriptor 여러 속성을 처리하는 것이 문제입니다. Type.GetCustomAttributes.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top