2013-05-08 95 views
1

我想創建一個返回新對象並將委託作爲參數的方法。 代表應該使用該對象進行操作。 我想不把該對象作爲參數,並使用返回我的函數的對象。 是否有可能使這段代碼運行?如何從委託訪問變量?

public class ActionContext 
    { 
     public Action Action; 
     public int Variable = 0; 
    } 

    public ActionContext Create(Action action) 
    { 
     return new ActionContext(){ Action = action };  
    } 

    public void Test() 
    { 
     // I don't want provide ActionContext through delegate(ActionContext) 
     ActionContext context = Create(delegate 
     { 
      //ERROR: Use of unassigned local variable 'context' 
      context.Variable = 10; 
     }); 

     context.Action.Invoke(); 
    } 
+0

http://stackoverflow.com/questions/428617/what-are-closures-in-net – Aron 2013-05-08 09:52:30

回答

1
public class ActionContext 
{ 
    public Action Action; 
    public int Variable = 0; 
    public delegate void Foo(ref int i); 

    public ActionContext(ActionContext.Foo action) 
    { 
     Action =() => action(ref this.Variable);  
    } 
} 



public void Test() 
{ 
    // I don't want provide ActionContext through delegate(ActionContext) 
    ActionContext context = new ActionContext(
     (ref int variable) => variable = 10); 

    context.Action.Invoke(); 
} 
2

它改成這樣:

public void Test() 
{ 
    ActionContext context = null; // Set it to null beforehand 
    context = Create(delegate 
    { 
     context.Variable = 10; 
    }); 

    context.Action.Invoke(); 
} 

並將其編譯和工作正常。

在您的代碼版本中,編譯器嘗試使用(capture)該變量仍未分配時。但是我們知道context變量在匿名方法被調用之前被分配。所以我們可以給它分配一個臨時值,以便編譯器不會抱怨。

+0

謝謝你,我雖然沒有實現它沒有初始申報 – 2013-05-09 20:11:44

+1

@Vlad不客氣的方式。如果答案能夠幫助您解決問題,您可以將答案標記爲已接受。請閱讀[常見問題]。順便說一句,歡迎來到StackOverflow :-) – 2013-05-10 08:41:54

+0

其實,我知道這個解決方案,但認爲它可能使這沒有初始定義。你的答案可以幫助那些新的C#人,所以我會接受它不會混淆他們。無論如何,如果你會發現別的東西 - 隨時分享你的想法。謝謝! – 2013-05-26 10:30:53

1
public class ActionContext 
{ 
    public Action Action; 
    public int Variable = 0; 


    public Func<ActionContext> Create(Action action) 
    { 
     return (() => { Action = action; return this; }); 
    } 


    public void Test() 
    { 
     // I don't want provide ActionContext through delegate(ActionContext) 
     var context = Create(() => { Variable = 10; }); 
    context().Action.Invoke(); 
    } 

} 
+0

嗨瓦列裏,我該怎麼聯繫你? – 2015-07-03 04:51:47