Ant*_*ean 6 c# anonymous-methods out-parameters
以下方法无法编译.Visual Studio警告"可能无法在匿名方法中使用out参数".该WithReaderLock(Proc action)方法需要一个delegate void Proc().
public Boolean TryGetValue(TKey key, out TValue value)
{
Boolean got = false;
WithReaderLock(delegate
{
got = dictionary.TryGetValue(key, out value);
});
return got;
}
Run Code Online (Sandbox Code Playgroud)
获得这种行为的最佳方法是什么?(请不要提供有关线程安全词典的建议,这个问题一般是为了解决out参数问题).
Mar*_*ell 11
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;
}
Run Code Online (Sandbox Code Playgroud)
(编辑 - 小虫子)
有关信息,在.NET 3.5中,您可能希望使用Action委托而不是自己编写代理,因为人们会更多地识别它.即使是在2.0,有很多void Foo()代表:ThreadStart,MethodInvoker,等等-但是Action是最容易遵循;-p