C# 不指定类型的泛型方法
好吧,我是一个开始使用 C# 的 Java 人员,我正在编码并开始制作一个通用方法,我编写的内容可以运行和编译,但这违背了我所知道的关于泛型应该如何工作的所有内容,所以我希望有人可以解释这一点对我来说:
所以我定义了一个通用方法,如下所示:
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);
}
代码如何能够在不指定泛型类型的情况下进行编译? 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;
}
But the weird thing to me is that I can call this generic method without ever specifying T
and it will work:
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);
}
How is it the code is able to compile without ever specifying the generic type? Does C# infer the type at runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,它是在编译时推断的 - 使用您提供的 IEnumerable中的泛型类型参数,该参数在编译时已知。一般来说,有关泛型和类型参数的一切都是在编译时指定的。如果存在任何类型的不匹配,编译器将抱怨并且您的代码将无法编译。
在某些边缘情况下,您必须显式指定类型,这些情况仅在使用重载方法的极少数情况下发生,有时会使用类型参数的多种组合。
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.
C# 编译器通常可以在编译时推断泛型类型。当它可以做到这一点时,您不需要指定泛型方法的类型。
这是使 LINQ 变得“可用”的一个主要部分。如果没有编译时类型推断,查询将类似于:
而不是能够编写:
The C# compiler can often infer the generic type at compile time. When it can do this, you do not need to specify the type for a generic method.
This is a major part of what makes LINQ "usable". Without compile time type inference, queries would look like:
Instead of being able to write: