2015-05-29 74 views
0

我想爲IDictionary - GetValue做一個超酷擴展,如果沒有設置,默認值爲null。這裏是我想出了一個代碼(不工作):C#中擴展方法中的可枚舉嵌套類型

public static TValue GetValue<TKey, TValue> (this IDictionary<TKey, 
    TValue> dictionary, TKey key, TValue defaultValue = null) 
{ 
    TValue value; 
    return dictionary.TryGetValue(key, out value) 
     ? value 
     : defaultValue; 
} 

如何使這個只有nullables? (比如,不包括int等)。

回答

7

你的意思是隻reference types。添加where T: class如下:

public static TValue GetValue<TKey, TValue> (this IDictionary<TKey, 
    TValue> dictionary, TKey key, TValue defaultValue = null) 
    where TValue: class 
{ 

但是你可以用值類型這項工作也是如此,通過使用default(TValue)指定默認:

public static TValue GetValue<TKey, TValue>(this IDictionary<TKey, 
    TValue> dictionary, TKey key, TValue defaultValue = default(TValue)) 
{ 
    TValue value; 
    return dictionary.TryGetValue(key, out value) 
     ? value 
     : defaultValue; 
} 

當然,只有做到這一點,如果你真的想要它使用所有可能的類型,而不僅僅是參考類型。

+0

很好地向OP說明限制真正打算做什麼。 「可空」意味着它們必須是引用類型。 – Yuck

0

使用class constraint

public static TValue GetValue<TKey, TValue> (this IDictionary<TKey, 
    TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class 
{ 
    TValue value; 
    return dictionary.TryGetValue(key, out value) 
     ? value 
     : defaultValue; 
} 
+0

注意:類約束應該在'TValue'而不是'TKey' –

2

您可以對您的類型參數使用約束(MSDN Type Constraints)。你想在這裏什麼是class約束,就像這樣:

public static TValue GetValue<TKey, TValue> (this IDictionary<TKey, 
TValue> dictionary, TKey key, TValue defaultValue = null) where TValue : class 

這適用於引用類型,這是你真正想要的。可爲空將意味着像int?這樣的工作。