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();
    }
4

3 回答 3

2

将其更改为:

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

    context.Action.Invoke();
}

它编译并且工作正常。

在您的代码版本中,编译器会在变量仍未分配时尝试使用(捕获)变量。但是我们知道context变量是在匿名方法被调用之前被赋值的。所以我们可以给它分配一个临时值,这样编译器就不会抱怨了。

于 2013-05-08T09:58:43.120 回答
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();
   }

}
于 2013-05-10T11:53:33.230 回答
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();
}
于 2013-05-08T09:56:37.763 回答