2010-02-19 2 views
11

내 사용자 지정 특성의 생성자 안에 사용자 지정 특성이 있습니다. 내 특성의 속성 값을 특성이 적용된 속성의 형식으로 설정하려고합니다. 속성이 있던 구성원에 액세스 할 수있는 방법이 있습니다. 내 속성 클래스 내부에서 적용됩니까?내부 특성 생성자에서 특성이 적용된 멤버 가져 오기?

+0

당신이 간단하게 사용 사례를 설명 할 수 있습니까? – Tanmay

+1

해결하려는 문제에 대해 더 자세하게 설명 할 수있는 경우 대체 솔루션을 제공 할 수 있습니다. –

+1

고마워, 내가 다른 방식으로 같은 것을 얻을 수있는 방법을 알고 있지만, 코드가 더 깨끗해지기 때문에 가능한지 알고 싶었다. – ryudice

답변

13

속성은 그렇게 작동하지 않습니다. 두렵습니다. 그것들은 단지 개체에 붙어 있지만 그것들과 상호 작용할 수없는 "마커"일뿐입니다.

속성 자체는 일반적으로 동작이없고 단순히 첨부 된 유형의 메타 데이터 만 포함해야합니다. 속성과 관련된 모든 동작은 속성의 존재를 찾고 작업을 수행하는 다른 클래스에 의해 제공되어야합니다.

속성이 적용되는 유형에 관심이있는 경우 해당 정보는 속성을 얻기 위해 반영됩니다.

+0

Reflection을 통해 사용자 지정 특성을 가져올 때 형식을 알면 세상 끝이 아니지만 GetCustomAttribute에 전달 된 Type도 System.Attribute에 저장되는 경우 "nice"가됩니다. –

0

다음 작업을 수행 할 수 있습니다. 그것은 간단한 예입니다.

//target class 
public class SomeClass{ 

    [CustomRequired(ErrorMessage = "{0} is required", ProperytName = "DisplayName")] 
    public string Link { get; set; } 

    public string DisplayName { get; set; } 
} 
    //custom attribute 
    public class CustomRequiredAttribute : RequiredAttribute, IClientValidatable 
{ 
    public string ProperytName { get; set; } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
     var propertyValue = "Value"; 
     var parentMetaData = ModelMetadataProviders.Current 
      .GetMetadataForProperties(context.Controller.ViewData.Model, context.Controller.ViewData.Model.GetType()); 
     var property = parentMetaData.FirstOrDefault(p => p.PropertyName == ProperytName); 
     if (property != null) 
      propertyValue = property.Model.ToString(); 

     yield return new ModelClientValidationRule 
     { 
      ErrorMessage = string.Format(ErrorMessage, propertyValue), 
      ValidationType = "required" 
     }; 
    } 
} 
0

그것은 CallerMemberName를 사용 .NET 4.5에서 가능 :

[SomethingCustom] 
public string MyProperty { get; set; } 

이 그런 다음 속성이

:

[AttributeUsage(AttributeTargets.Property)] 
public class SomethingCustomAttribute : Attribute 
{ 
    public StartupArgumentAttribute([CallerMemberName] string propName = null) 
    { 
     // propName = "MyProperty" 
    } 
} 
관련 문제