c# - 其中 T : IEnumerable<T> method constraint

标签 c# generics collections constraints

我时常试图折磨 C# 编译器。今天我想到了这个:

static void CallFirst<T>(T a) where T : IEnumerable<T>
{
    a.First().ToString();
}

这是一个简单的错误,因为我想创建以集合为参数的泛型方法,当然应该如下所示:

static void CallFirst2<T>(IEnumerable<T> a)
{
    a.First().ToString();
}

无论如何,是否可以调用 CallFirst() 方法?每次通过集合,都期望集合的集合。

如果不是,是不是应该认为是编译时错误?

最佳答案

当然:

class Test : IEnumerable<Test>
{
    IEnumerator<Test> IEnumerable<Test>.GetEnumerator()
    {
        throw new NotImplementedException();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

    ...

var test = new Test();
CallFirst(test);

关于c# - 其中 T : IEnumerable<T> method constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26973337/

相关文章:

c# - 将 Dictionary<string, string> 转换为 xml 的简单方法,反之亦然

java - 泛型的意外行为

java - 维护可以修改的时间片的有序列表(列表仍应排序)

java - 我的 Treeset 仅添加 1 个类对象

c# - 如何改变不同工作地点的连接字符串

c# - 将 Elvis 运算符与 string.Equals 结合使用

c# - 为什么在 web api 中返回具有一对多关系的实体会导致错误?

java - Enthuware 示例 - hashCode 和 equals

c# - 通用约束忽略协方差

java - 比较两种不同类型的 ArrayLists 以找到共同的数据