【发布时间】:2009-08-17 13:33:23
【问题描述】:
如何捕获变量?
或者,我可以存储对对象引用的引用吗?
通常,方法可以使用 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();
}
...但也许有更好的主意。
【问题讨论】:
-
您的解决方案对我来说似乎很不错...
标签: c# .net argument-passing