2011-01-11 61 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是一个公共密钥(以及是参考型),这可能是不期望的方法。

相关问题