StackOverflow上的几个C#问题询问如何使用out或ref参数创建匿名委托/ lambdas .例如,见:
为此,您只需指定参数的类型,如:
public void delegate D(out T p);
// ...
D a = (out T t) => { ... }; // Lambda syntax.
D b = delegate(out T t) { ... }; // Anonymous delegate syntax.
Run Code Online (Sandbox Code Playgroud)
我很好奇的是为什么明确要求类型.有这种情况的特殊原因吗?也就是说,从编译器/语言的角度来看,为什么不允许以下内容?
D a = (out t) => { ... }; // Lambda syntax -- implicit typing.
D b = delegate(out t) { ... }; // Anonymous delegate syntax -- implicit typing.
Run Code Online (Sandbox Code Playgroud)
甚至更好,只是:
D a = (t) …Run Code Online (Sandbox Code Playgroud) 以下方法无法编译.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参数问题).