我想创建一个返回新对象的方法,并将delegate作为参数。 代表应该使用该对象。 我想不把该对象作为参数并使用返回我的函数的对象。 是否可以运行此代码?
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 :(得分:2)
将其更改为:
public void Test()
{
ActionContext context = null; // Set it to null beforehand
context = Create(delegate
{
context.Variable = 10;
});
context.Action.Invoke();
}
它编译并正常工作。
在您的代码版本中,编译器在仍未取消分配时尝试使用( capture )变量。但是我们知道在调用匿名方法之前正在分配context
变量。所以我们可以为它分配一个临时值,这样编译器就不会抱怨。
答案 1 :(得分: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 :(得分: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();
}
}