如何捕获变量 (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();
}
...但也许有更好的主意。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不能有 ref 字段。例如,请参见 http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx(向下滚动到其中写着“这解释了为什么你不能创建“ref int”字段......”)。
lambda 或委托可能是您最好的选择。我想你可以使用事件,或者观察者接口,或者其他东西。
You can't have a ref field. See, for example, http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx (scroll down to where it says "This explains why you cannot make a “ref int” field....").
A lambda or a delegate is probably your best bet here. I suppose you could use an event, or an observer interface, or something.
使用具有 1 个元素的数组
您还可以使用包装器“int?” - 原谅它们可以为空,但请记住它总是传递引用。
Use Array with 1 element
Also You can use wrapper "int?" - forgive them nullable, but remember that it always passed over reference.
这是一个猜测(我还没有尝试/测试过):
如果上面的方法不起作用,那么就说 Job 构造函数将委托作为其参数,并在 Bar 类内部构造委托(并传递委托而不是传递委托)传递 ref 参数)。
Here's a guess (I haven't tried/tested it):
If the above doesn't work, then say that the Job constructor takes a delegate as its parameter, and construct the delegate inside the Bar class (and pass the delegate instead of passing the ref parameter).