如何捕获变量?
或者,我可以存储对对象引用的引用吗?
通常,方法可以使用ref
关键字更改其外部的变量。
void Foo(ref int x)
{
x = 5;
}
void Bar()
{
int m = 0;
Foo(ref m);
}
这是清晰而直接的。
现在让我们考虑一个类来实现同样的事情:
class Job
{
// ref int _VarOutsideOfClass; // ?????
public void Execute()
{
// _VarOutsideOfClass = 5; // ?????
}
}
void Bar()
{
int m = 0;
var job = new Job()
{
_VarOutsideOfClass = ref m // How ?
};
job.Execute();
}
我该如何正确写?
评论:我不能把它变成一个带ref
参数的方法,因为当它出现在队列中时,通常Execute()
会稍后在不同的线程中调用。
目前,我制作了一个包含大量 lambda 的原型:
class Job
{
public Func<int> InParameter;
public Action<int> OnResult;
public void Execute()
{
int x = InParameter();
OnResult(5);
}
}
void Bar()
{
int m = 0;
var job = new Job()
{
InParameter = () => m,
OnResult = (res) => m = res
};
job.Execute();
}
...但也许有更好的主意。