为什么我不需要在C#中指定类型参数?
问题描述:
我有一个函数,它采用泛型类型参数。这很简单:为什么我不需要在C#中指定类型参数?
private static void Run<T>(IList<T> arg)
{
foreach (var item in arg)
{
Console.WriteLine(item);
}
}
我发现我可以调用这个函数没有指定类型参数:
static void Main(string[] args)
{
var list = new List<int> { 1, 2, 3, 4, 5 };
//both of the following calls do the same thing
Run(list);
Run<int>(list);
Console.ReadLine();
}
这编译和运行就好了。为什么这个工作没有指定类型参数?代码如何知道T
是一个int?有没有这个名字?
答
通过编译器可以推断你传入的参数类型的方法参数推断出类型参数..
从docs:
编译器可以基于您传入的参数的方法推断出类型参数;它不仅可以从 约束或返回值
埃里克利珀也有仿制药超负荷选择一个有趣的阅读推断类型参数: http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx
答
接受的答案是正确的。欲了解更多的背景信息,这里有一些资源给你:
我的视频解释的类型推断的是如何改变C#3.0:
http://ericlippert.com/2006/11/17/a-face-made-for-email-part-three/
我们怎么知道该类型推理过程不会去进入无限循环?
http://ericlippert.com/2012/10/02/how-do-we-ensure-that-method-type-inference-terminates/
为什么不限制类型推断的过程中考虑?特别阅读评论。
这是因为编译器推断从你传递的列表类型 –
2014-10-01 17:25:18