2008-12-21 29 views
5

以下方法不能編譯。 Visual Studio警告「一個輸出參數不能在匿名方法中使用」。 WithReaderLock(Proc action)方法需要delegate void Proc()如何規避在匿名方法塊中使用out參數?

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

得到此行爲的最佳方法是什麼? (請不要提供關於線程安全字典的建議,這個問題一般是爲了解決out參數問題)。

回答

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; 
} 

(編輯 - 小bug)

有關信息,在.NET 3.5,你可能想使用的,而不是滾動您自己的Action代表,因爲人們會更加認識到它。即使在2.0中,也有很多void Foo()代表:ThreadStart,MethodInvoker等 - 但Action是最容易遵循的;-p

+0

對不起原始版本中的小故障;固定 – 2008-12-21 20:50:46

1

簡單的答案是隻複製方法內部的邏輯。但是,接下來我們要擴展DRY原則,並且必須在兩種方法中保持行爲。

public Boolean TryGetValue(TKey key, out TValue value) 
{ 
    internalLock.AcquireReaderLock(Timeout.Infine); 
    try 
    { 
     return dictionary.TryGetValue(key, out value); 
    } 
    finally 
    { 
     internalLock.ReleaseReaderLock(); 
    } 
} 
相關問題