【问题标题】:C# generic constrain : type cannot be inferred from usage [duplicate]C# 泛型约束:无法从用法推断类型 [重复]
【发布时间】:2012-04-18 19:08:45
【问题描述】:

可能重复:
No type inference with generic extension method

我有一个带有约束的通用函数,它返回集合中的第一个对象:

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);

不知道为什么,有人可以帮忙吗?谢谢。

【问题讨论】:

标签: c# generics


【解决方案1】:

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

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

【讨论】:

  • 谢谢。虽然有点失望,但在 java 中是可能的。
猜你喜欢
  • 1970-01-01
  • 2012-02-19
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 2020-07-30
  • 2022-11-23
  • 2010-11-01
  • 1970-01-01
相关资源
最近更新 更多