C#泛型约束:无法从用法推断类型
可能重复:C#泛型约束:无法从用法推断类型,c#,generics,C#,Generics,可能重复: 我有一个带约束的泛型函数,它返回集合中的第一个对象: 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
我有一个带约束的泛型函数,它返回集合中的第一个对象:
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;
}
静态T优先(L列表)
其中L:I收集
T:什么类型
{
tr=默认值(T);
if(list!=null&&list.Count>0)
{
如果(list.Count==1)
{
r=list.First();
}
其他的
{
//抛出一些异常。。。
}
}
返回r;
}
但当我对集合使用它时,代码将不会编译,并给我一个“无法从用法推断类型”错误:
ICollection list=funcReturnCollectionOfSomeType();
SomeType o=第一个(列表);
不知道为什么,有人能帮忙吗?谢谢。它无法从类型L向后推断类型t。请使用单个通用参数:
static T first<T>(ICollection<T> list)
where T : SomeType
{
...
static T first(i收集列表)
T:什么类型
{
...
特别要看。谢谢。不过有点失望,在java中这是可能的。
static T first<T>(ICollection<T> list)
where T : SomeType
{
...