我想創建一個返回新對象並將委託作爲參數的方法。 代表應該使用該對象進行操作。 我想不把該對象作爲參數,並使用返回我的函數的對象。 是否有可能使這段代碼運行?如何從委託訪問變量?
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();
}
http://stackoverflow.com/questions/428617/what-are-closures-in-net – Aron 2013-05-08 09:52:30