Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

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

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

public Boolean TryGetValue(TKey key, out TValue value)
{
    Boolean got = false;
    WithReaderLock(delegate
    {
        got = dictionary.TryGetValue(key, out value);
    });
    return got;
}

What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...