简体   繁体   中英

How can I access variable from delegate?

I want to create a method which returns new object and takes delegate as parameter. Delegate should operate with that object. I would like to not put that object as parameter and use object that returns my function. Is it possible to make this code running?

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

Change it to this:

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

    context.Action.Invoke();
}

And it compiles and works fine.

In your version of the code, the compiler tries to use ( capture ) the variable when it is still unassigned. But we know that the context variable is being assigned before the anonymous method is going to be called. So we can assign a temporary value to it so that the compiler doesn't complain.

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM