C# 基于属性的属性拦截。怎么用?
我有一个抽象的实体类,负责为每个实体实例生成和返回一个唯一的键。密钥生成成本有点高,并且基于具体实体的属性值。我已经用C# 基于属性的属性拦截。怎么用?,c#,unity-interception,method-interception,C#,Unity Interception,Method Interception,我有一个抽象的实体类,负责为每个实体实例生成和返回一个唯一的键。密钥生成成本有点高,并且基于具体实体的属性值。我已经用keymberattribute标记了参与密钥生成的属性,所以每次用keymberattribute修饰的属性更改时,我只需要将EntityBase.key=null 我得到了这样的基类: public abstract class EntityBase : IEntity { private string _key; public string Key {
keymberattribute
标记了参与密钥生成的属性,所以每次用keymberattribute
修饰的属性更改时,我只需要将EntityBase.key
=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; }
}
每次属性值更改时,我都需要设置
keymberAttribute
以将EntityBase.Key
设置为null
。看看面向方面编程(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。谢谢。只是在反思方面有些问题。然而,由于您的代码示例再次尝试了这种方法,我发现了这一点: