Update ref parameter inside anonymous method

*爱你&永不变心* 提交于 2020-01-03 08:44:08

问题


Is there a workaround to update a ref parameter inside an anonymous method?

I know that the an anonymous method doesn't allow access to ref parameters of the outer scope, but is there another way to do it? I am using an external library for the MessageStream so cannot alter the arguments of the delegate...

void DoWork(ref int count)
{
    MessageStream Stream = new MessageStream();
    Stream.MessageReceived += (o, args) =>
    {
        //Error cannot use ref or out parameter inside anonymous method
        count++;
    };
}

回答1:


In your case there is no viable work-around to this problem: by the time the Stream.MessageReceived event fires, the count may be well out of scope in the caller of your DoWork function.

In situations like that you should encapsulate the count in an object, and keep a reference to that object in both the event handler and in the caller, like this:

class Counter {
    public int Value {get;private set;}
    public void Increment() {Value++;}
}
void DoWork(Counter count) {
    MessageStream Stream = new MessageStream();
    Stream.MessageReceived += (o, args) => {
        count.Increment();
    };
}



回答2:


If you want to have the delegate update a variable from an outter scope, pass a lambda that sets the value instead of passing the count by ref.

//shared var
private static int _count = 0;

//call your method
DoWork(() => _count++);  //instead of DoWork(ref _count);


void DoWork(Action countInc)
{
    MessageStream Stream = new MessageStream();
    Stream.Activated += (o, args) => countInc();
}


来源:https://stackoverflow.com/questions/23630765/update-ref-parameter-inside-anonymous-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!