gpt4 book ai didi

c# - 其中 T : IEnumerable method constraint

转载 作者:太空狗 更新时间:2023-10-29 23:38:37 26 4
gpt4 key购买 nike

我时常试图折磨 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com