如何捕获变量?
或者,我可以存储对象引用的引用吗?如何捕获变量(C#)
通常情况下,一种方法可以使用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();
}
...但也许有一个更好的主意。
您的解决方案对我来说似乎很不错... – 2009-08-17 13:38:58