2011-01-11 60 views
2

我使用在所呈現的支點方法: http://www.extensionmethod.net/Details.aspx?ID=147可空參數類型<T>爲通用方法?

我的問題是:如何使用可空類型作爲第二個通用密鑰?

public static Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>> Pivot<TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TFirstKey> firstKeySelector, Func<TSource, TSecondKey> secondKeySelector, Func<IEnumerable<TSource>, TValue> aggregate) { 
     var retVal = new Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>>(); 

     var l = source.ToLookup(firstKeySelector); 
     //l.Dump("Lookup first key"); 
     foreach (var item in l) { 
      var dict = new Dictionary<TSecondKey, TValue>(); 
      retVal.Add(item.Key, dict); 
      var subdict = item.ToLookup(secondKeySelector); 
      foreach (var subitem in subdict) { 
       dict.Add(subitem.Key, aggregate(subitem)); 
      } 
     } 

     return retVal; 
    } 
+0

什麼是您的編譯或運行時錯誤? – Spence 2011-01-11 09:33:40

回答

0

你可以在你的通用聲明中使用的Nullable<T>,這將限制你對你的方法使用Nullable明確。

public static Dictionar<TFirstKey, Dictionary<Nullable<TSecondKey>, TValue>> Pivot<TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TFirstKey> firstKeySelector, Func<TSource, Nullable<TSecondKey>> secondKeySelector, Func<IEnumerable<TSource>, TValue> aggregate) 
    where TSecondKey : struct 
{} 

隨着你的使用Nullable<T>,你必須爲T約束重複到您的實現。

請注意,Dictionary可能不滿意null鍵。

+0

如果字典對於null鍵不滿意,那麼在這裏使用`Nullable ```絕對*沒有任何好處。這隻會增加每個值的額外開銷,當**我們知道**時,每個值都必須是非空的。它也避免了使用`string`作爲關鍵字;主要使用兩個鍵; `string`和`int`。 – 2011-01-11 09:37:38

+0

這不行,請檢查IDictionary`2文檔:http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx。這個界面沒有反轉,所以你不能將Dictionary 轉換爲字典,... – 2011-01-11 09:38:23

0

我不確定我是否理解你,但你應該使用泛型類型約束來聲明類型T是Nullable。

事情是這樣的:

public void Method<T> where T : Nullable<T> 
{ 
} 

也許我錯了,因爲我在一些計算機,而無需Visual Studio和我不能嘗試!

3

你應該能夠只要值不爲空只是通常使用可空類型 - 但你不能使用null(或空Nullable<T>)作爲重點 - 它根本就」工作。

確保(在調用代碼中)secondKeySelector總是返回非空值;在Nullable<T>的情況下,也許通過呼叫x => x.Foo.Value(如果你明白我的意思)。

另一種方法是,以聲明的方式排除Nullable<T>這裏,通過添加where TSecondKey : struct - 但由於string是一個公共密鑰(以及是參考型),這可能是不期望的方法。

相關問題