我有一个函数,它采用泛型类型参数。这很简单:为什么我不需要在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?有没有这个名字?
这是因为编译器推断从你传递的列表类型 –
2014-10-01 17:25:18