2011-11-10 9 views
1

我喜歡在代碼中使用c#的自動屬性,因爲我發現它更好。最近有一個想法,我將如何設法使用自動屬性,但將值存儲在Session中。對於簡單的幾個原因: - 避免會話項目名稱 錯別字 - 避免額外的代碼 - 可能延長到其他店一樣的ViewState等任何人都試過實現C#。自動屬性會存儲在會話中的價值?

到目前爲止我想到的屬性將是最好的選擇。只是好奇,如果有人在我挖掘並開始實施它之前嘗試過這一點。

例如

[Session] 
public int Id{get;set;} 

代替

public int Id{ get{return Session["Id"];} set{Session["Id"] = value;}} 

回答

4

不,你不能做到這一點。

自動實現的屬性只有當期望的實現是由字段支持的「平凡」屬性時工作。這就是編譯器所支持的一切。幾乎所有可以「調整」自動實現的屬性的唯一方法是以不同的方式設置getter和setter的可訪問性。

當然,現在你可以編寫代碼來自動創建會話中的值並在特定的方法調用時將其保存到會話中 - 但這不是一回事。

1

你不能在香草C#中做到這一點,但你可以通過方面得到你的效果。

Postsharp是一個很好的起點AOP:

http://www.sharpcrafters.com/

1

你不能做到這一點使用自動實現的屬性,正如其他人說。 Butyou可以使用抽象屬性和Castle DynamicProxy(或類似的)來做類似的事情。

例如,你可以有這樣的代碼:

public abstract class Foo : IWithSession 
{ 
    public IDictionary<string, object> Session { get; private set; } 

    protected Foo() 
    { 
     Session = new Dictionary<string, object>(); 
    } 

    [Session] 
    public abstract int Id { get; set; } 
} 

,將真正實現getter和setter看起來像這樣的攔截器:

class SessionInterceptor : IInterceptor 
{ 
    public void Intercept(IInvocation invocation) 
    { 
     var method = invocation.Method; 

     bool isGetter = method.IsSpecialName && method.Name.StartsWith("get_"); 
     bool isSetter = method.IsSpecialName && method.Name.StartsWith("set_"); 

     if (isGetter || isSetter) 
     { 
      string propertyName = method.Name.Substring(4); 

      var property = invocation.TargetType.GetProperty(propertyName); 

      bool hasSessionAttribute = property.GetCustomAttributes(typeof(SessionAttribute), false).Any(); 

      if (hasSessionAttribute) 
      { 
       var session = ((IWithSession)invocation.InvocationTarget).Session; 

       if (isGetter) 
       { 
        invocation.ReturnValue = session[propertyName]; 
        return; 
       } 
       else 
       { 
        session[propertyName] = invocation.Arguments[0]; 
        return; 
       } 
      } 
     } 

     invocation.Proceed(); 
    } 
} 
+0

會盡量做到一些事情,謝謝指出方向。 –