Skip to main content
 首页 » 编程设计

c#之如何从委托(delegate)访问变量

2024年02月13日10EasonJim

我想创建一个返回新对象并将委托(delegate)作为参数的方法。 委托(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(); 
} 

它编译并运行良好。

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