2013-07-06 3 views
1

클래스 범위의 각 객체에 대해 ID 번호 키를 생성하는 속성을 만들려고합니다. 그래서 어떤 클래스가 속성과 연결된 매개 변수를 포함하고 있는지 알아야합니다. 저를 매개 변수로 보내지 않고 IdentityAttribute 생성자 (이 경우 SampleMethod에서) 기본 클래스의 종류를 얻을 수있는 방법이속성 속성에서 기본 클래스에 액세스

class SampleModel 
{ 
    [Identity(typeof(SampleModel))] 
    public int Id { get; set; } 
} 


public class IdentityAttribute : Attribute 
{ 
    private readonly int _step; 
    private readonly Type _objectType; 

    public IdentityAttribute(Type type) 
    { 
     _step = 1; 
     _objectType = type; 
    } 

    public object GenerateValue() 
    { 
     return IdentityGenerator.GetGenerator(_objectType).GetNextNum(_step); 
    } 
} 

하지만 난 궁금하네요 : 나는 이런 식으로 뭔가를 만들?

답변

1

Attribute의 인스턴스는 꾸미고있는 것을 알지 못합니다.

는 그러나 당신이 외부 정보를 주입 할 수있는 사용에 너무 의존 인스턴스가하는를 만드는 코드 :

var identityAttribute = (IdentityAttribute)Attribute.GetCustomAttribute(...); 

// If you can call GetCustomAttribute successfully then you can also easily 
// find which class defines the decorated property 
var baseClass = ... ; 

// And pass this information to GenerateValue 
var value = identityAttribute.GenerateValue(baseClass); 
+0

덕분에, 나는 이런 식으로 할 것입니다. – us3r

관련 문제