我如何从委托访问变量

本文关键字:访问 变量 | 更新日期: 2023-09-27 18:12:41

我想创建一个返回新对象的方法,并将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();
    }

我如何从委托访问变量

改成:

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

它可以编译并正常工作。

在你的代码版本中,编译器试图使用(capture)变量,当它仍然未赋值时。但是我们知道context变量是在匿名方法被调用之前被赋值的。所以我们可以给它赋一个临时值,这样编译器就不会报错了。

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