0

すべての Entity インスタンスの一意のキーを生成して返すエンティティの抽象クラスがあります。キーの生成は少しコストがかかり、具体的なエンティティのプロパティ値に基づいています。キー生成に参加しているプロパティを既にマークしているKeyMemberAttributeので、必要なのは、装飾されたプロパティが変更EntityBase.Keyされるたびに = null にすることだけです。KeyMemberAttribute

したがって、次のような基本クラスを取得しました。

public abstract class EntityBase : IEntity
{
    private string _key;
    public string Key {
        get {
            return _key ?? (_key = GetKey);
        }
        set {
            _key = value;
        }
    }
    private string GetKey { get { /* code that generates the entity key based on values in members with KeyMemberAttribute */ } };
}

次に、具体的なエンティティを次のように実装しました

public class Entity : EntityBase
{

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

    [KeyMember]
    public string AnotherProperty { get; set; }

}

プロパティ値が変更されるたびKeyMemberAttributeに を に設定する必要があります。EntityBase.Keynull

4

1 に答える 1

2

PostSharp などの Aspect Oriented Programming (AOP) フレームワークを見てください。PostSharp では、クラス、メソッドなどを装飾するために使用できる属性を作成できます。

このような属性は、セッターの実行前と終了後にコードを挿入するようにプログラムできます。

たとえば、postSharp を使用すると、次のように属性を定義できます。

[Serializable] 
public class KeyMemberAttribute : LocationInterceptionAspect 
{ 

    public override void OnSetValue(LocationInterceptionArgs args) 
    {   
      args.ProceedSetValue();
      ((EntityBase)args.Instance).Key=null;
    }
}

したがってKeyMemberAttribute、キーで装飾されたプロパティを呼び出すたびに、null に設定されます。

于 2014-09-21T21:11:35.543 に答える