2012-04-18 74 views
1

Possible Duplicate:
No type inference with generic extension methodC#泛型约束:类型不能从使用

推断出我有约束泛型函数返回的第一个对象的集合中:

static T first<T, L>(L list) 
where L : ICollection<T>    
where T : SomeType 
{ 
     T r = default(T); 
     if (list != null && list.Count>0) 
     { 
      if (list.Count == 1) 
      { 
       r = list.First(); 
      } 
      else 
      { 
       //throw some exception ... 
      } 
     } 
     return r; 
} 

但是当我用它对付一个集合代码将不会编译,并给我一个“类型无法推断使用”错误:

ICollection<SomeType> list = funcReturnCollectionOfSomeType(); 
SomeType o = first(list); 

无法弄清楚为什么,有没有人可以帮忙?谢谢。

+0

特别参见[Eric的答案](http://stackoverflow.com/a/7171527/572644 )。 – 2012-04-18 11:04:54

回答

2

它不能从类型L.使用向后推断类型T一个泛型参数:

static T first<T>(ICollection<T> list) 
where T : SomeType 
{ 
    ... 
+1

谢谢。有点失望,在Java中是可能的。 – murphytalk 2012-04-19 00:05:31