我有一个实体的抽象类,负责为每个Entity实例生成和返回唯一键。密钥生成有点昂贵,并且基于具体实体的属性值。我已经使用KeyMemberAttribute
标记了参与密钥生成的属性,因此我需要的是每次使用EntityBase.Key
修饰的属性发生更改时KeyMemberAttribute
= null。
所以,我得到了这样的基类:
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.Key
设置为null
。
答案 0 :(得分:2)
查看面向方面编程(AOP)框架,例如PostSharp。 PostSharp允许您创建可用于装饰类,方法等的属性。
这样的属性可以编程为在你的setter执行之前和完成之后注入代码。
例如使用postSharp,您可以定义您的属性,如:
[Serializable]
public class KeyMemberAttribute : LocationInterceptionAspect
{
public override void OnSetValue(LocationInterceptionArgs args)
{
args.ProceedSetValue();
((EntityBase)args.Instance).Key=null;
}
}
因此,每次调用任何使用KeyMemberAttribute
修饰的属性时,您的密钥都将设置为null。