2014-09-21 54 views
0

我有它負責生成和返回的每一個實體實例的唯一關鍵實體的抽象類。密鑰生成有點昂貴,並且基於具體實體的屬性值。我已經參加標記中的屬性密鑰生成與KeyMemberAttribute因此,所有我需要的是每一個屬性飾有KeyMemberAttribute變化的時間,使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; } 

} 

我需要做KeyMemberAttribute設置EntityBase.Keynull每時間屬性值更改。

回答

2

看一看的面向方面編程(AOP)框架,如PostSharp。 PostSharp允許您創建可用於修飾類,方法等的屬性。

這樣的屬性可以通過編程的setter方法執行之前和之後的成品注入代碼。

例如用postSharp你可以定義你的屬性,如:所以在每次調用飾KeyMemberAttribute您的密鑰將被設置爲null的任何屬性

[Serializable] 
public class KeyMemberAttribute : LocationInterceptionAspect 
{ 

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

+0

感謝。只是有一些反射問題。然而,由於有另一個去使用這種方法因您的代碼示例使我發現這一個:http://doc.postsharp.net/multicast-reflection – 2014-09-21 21:56:03