0

如何捕获变量?
或者,我可以存储对对象引用的引用吗?

通常,方法可以使用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();
}

...但也许有更好的主意。

4

3 回答 3

2

你不能有一个 ref 字段。例如,请参阅http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx(向下滚动到显示“这解释了为什么你不能创建一个“ref int”字段......”)。

lambda 或委托可能是您最好的选择。我想你可以使用一个事件,或者一个观察者界面,或者其他东西。

于 2009-08-17T13:38:56.273 回答
1

使用 1 个元素的数组

class Job{
int[] _VarOutsideOfClass = new int[1];

您也可以使用包装器“int?” - 原谅它们可以为空,但请记住它总是通过引用。

于 2009-08-17T13:38:18.133 回答
0

这是一个猜测(我还没有尝试/测试过):

class Job
{
  Action<int> m_delegate;

  public Job(ref int x)
  {
    m_delegate = delegate(int newValue)
    {
      x = newValue;
    };
  }

  public void Execute()
  {
    //set the passed-in varaible to 5, via the anonymous delegate
    m_delegate(5);
  }
}

如果上述方法不起作用,则说 Job 构造函数将委托作为其参数,并在 Bar 类中构造委托(并传递委托而不是传递 ref 参数)。

于 2009-08-17T13:44:08.437 回答