1

クラス範囲内の各オブジェクトの ID 番号キーを生成する属性を作成しようとしています。したがって、属性に接続されたパラメーターがどのクラスに含まれているかを知る必要があります。私はこのようなものを作成します:

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);
    }
}

しかし、パラメーターとして送信せずに、IdentityAttribute コンストラクターで基本クラス (この場合は SampleMethod) の Type を取得できるメソッドがあるのでしょうか?

4

1 に答える 1

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);
于 2013-07-06T13:55:26.583 に答える