如何避免在匿名方法块中使用out参数?
以下方法无法编译。 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; }
获得这种行为的最佳方法是什么? (请不要提供有关线程安全词典的建议,这个问题一般用于解决out参数问题)。
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; }
(编辑 – 小虫子)
有关信息,在.NET 3.5中,您可能希望使用Action
委托而不是自己编写,因为人们会更多地识别它。 即使在2.0中,也有很多void Foo()
委托: ThreadStart
, MethodInvoker
等 – 但Action
最容易遵循;-p
简单的答案就是复制方法中的逻辑。 但后来我们延长了DRY原则并且必须在两种方法中保持行为。
public Boolean TryGetValue(TKey key, out TValue value) { internalLock.AcquireReaderLock(Timeout.Infine); try { return dictionary.TryGetValue(key, out value); } finally { internalLock.ReleaseReaderLock(); } }