using System;
namespace ConsoleApplication1
{
interface ITest
{
void TestMethod();
}
class TestType : ITest
{
//public testType(int i) {}
public void TestMethod()
{
Console.WriteLine("testing");
}
}
class test
{
public static void Foo<T>(T t)
where T: ITest
{
t.TestMethod();
}
}
class Class1
{
[STAThread]
static void Main(string[] args)
{
object o = new TestType();
Test.Foo(o); //compile-error
}
}
}
注意到那个 o对象的实际类型为TestType,继承了ITest接口,但是编译时仍然报错。也就是说对一个对象是否满足constraints的检查是在编译期完成的,并不涉及到运行期的型别信息。也就是说在C#中对泛型的实例化的检查和C++中一样,也是在编译期就完成了。
如此一来,空添加了Constraints那样的语法,却完全没有带来任何好处,而且把泛型本身的优势也给阉割了,实在想不到这样做的目的何在。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步