How to circumvent using an out parameter in an anonymous method block?

后端 未结 2 960
臣服心动
臣服心动 2020-12-11 06:06

The following method does not compile. Visual Studio warns \"An out parameter may not be used within an anonymous method\". The WithReaderLock(Proc action) meth

相关标签:
2条回答
  • 2020-12-11 06:44

    The simple answer is to just copy the logic inside the method. But then we stretch the DRY principle and have to maintain behavior inside both methods.

    public Boolean TryGetValue(TKey key, out TValue value)
    {
        internalLock.AcquireReaderLock(Timeout.Infine);
        try
        {
            return dictionary.TryGetValue(key, out value);
        }
        finally
        {
            internalLock.ReleaseReaderLock();
        }
    }
    
    0 讨论(0)
  • public bool TryGetValue(TKey key, out TValue value)
    {
        bool got = false;            
        TValue tmp = default(TValue); // for definite assignment
        WithReaderLock(delegate
        {
            got = dictionary.TryGetValue(key, out tmp);
        });
        value = tmp;
        return got;
    }
    

    (edited - small bug)

    For info, in .NET 3.5 you might want to use the Action delegate instead of rolling your own, since people will recognise it more. Even in 2.0, there are lots of void Foo() delegates: ThreadStart, MethodInvoker, etc - but Action is the easiest to follow ;-p

    0 讨论(0)
提交回复
热议问题