2014-10-01 110 views
0

我有一个函数,它采用泛型类型参数。这很简单:为什么我不需要在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?有没有这个名字?

+0

这是因为编译器推断从你传递的列表类型 – 2014-10-01 17:25:18

回答

3

接受的答案是正确的。欲了解更多的背景信息,这里有一些资源给你:

我的视频解释的类型推断的是如何改变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/

为什么不限制类型推断的过程中考虑?特别阅读评论。

http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

相关问题