C#泛型方法,而无需指定类型类型、方法

由网友(酷炸你爹)分享简介:好了,所以我是一个Java的人开始使用C#和我的编码,并开始做一个通用的方法和我写的运行和编译,但它违背了我知道的一切有关仿制药应该如何工作,所以我希望有人可以给我讲解一下:Ok so I'm a Java guy starting to use C# and I was coding and started mak...

好了,所以我是一个Java的人开始使用C#和我的编码,并开始做一个通用的方法和我写的运行和编译,但它违背了我知道的一切有关仿制药应该如何工作,所以我希望有人可以给我讲解一下:

Ok so I'm a Java guy starting to use C# and I was coding and started making a generic method and what I wrote runs and compiles but it goes against everything I know about how generics should work so I'm hoping someone can explain this to me:

所以,我有一个通用的方法定义如下:

So I have a generic method defined as follows:

public static List<T> CopyAsList<T>(IEnumerable<T> list, Object lockObject)  
{  
    if (list != null)  
    {  
        lock (lockObject)  
        {  
            return new List<T>(list);  
        }  
    }  
    return null;  
}  

但奇怪的事情对我来说,我可以调用这个通用的方法,而没有指定 T ,它会工作:

List<String> strings = new List<string>() { "a", "b", "c"};
List<int> ints = new List<int>() { 1,2,3};
object lockObject = new object();

foreach (string s in CopyAsList(strings, lockObject))
{
    Console.WriteLine(s);
}

foreach (int i in CopyAsList(ints, lockObject))
{
    Console.WriteLine(i);
}

它是如何在code能够永远不指定泛型类型来编译?请问C#中推断出类型在运行时?

How is it the code is able to compile without ever specifying the generic type? Does C# infer the type at runtime?

推荐答案

没有,推断在编译时 - 在泛型类型参数的的IEnumerable&LT; T&GT; 您供应的情况下,这被称为在编译时。一般的说,家居关于泛型和类型参数被指定在编译时。如果有任何形式的不匹配,编译器的会抱怨,你的code将无法编译。

No, it is inferred at compile time - the generic type parameter in the IEnumerable<T> you supply is used, which is known at compile time. Generally put, everything concerning generics and type parameters is specified at compile time. If there is mismatch of any kind, the compiler will complain and your code won't compile.

有,你必须明确指定类型的边缘情况,这些只发生在极少数情况下,重载的方法,有时类型参数的多种组合。

There are edge cases where you have to specify the types explicitly, these only occurs in rare circumstances with overloaded methods, sometimes with multiple combinations of type parameters.

阅读全文

相关推荐

最新文章