C# 泛型有什么好处,为什么要使用它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/77632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 11:15:31  来源:igfitidea点击:

What is cool about generics, why use them?

提问by MrBoJangles

I thought I'd offer this softball to whomever would like to hit it out of the park. What are generics, what are the advantages of generics, why, where, how should I use them? Please keep it fairly basic. Thanks.

我想我会把这个垒球提供给任何想把它打出公园的人。什么是泛型,泛型的优点是什么,为什么,在哪里,我应该如何使用它们?请保持它相当基本。谢谢。

采纳答案by ljs

  • Allows you to write code/use library methods which are type-safe, i.e. a List<string> is guaranteed to be a list of strings.
  • As a result of generics being used the compiler can perform compile-time checks on code for type safety, i.e. are you trying to put an int into that list of strings? Using an ArrayList would cause that to be a less transparent runtime error.
  • Faster than using objects as it either avoids boxing/unboxing (where .net has to convert value types to reference types or vice-versa) or casting from objects to the required reference type.
  • Allows you to write code which is applicable to many types with the same underlying behaviour, i.e. a Dictionary<string, int> uses the same underlying code as a Dictionary<DateTime, double>; using generics, the framework team only had to write one piece of code to achieve both results with the aforementioned advantages too.
  • 允许您编写类型安全的代码/使用库方法,即 List<string> 保证是字符串列表。
  • 由于使用了泛型,编译器可以对代码执行编译时检查以确保类型安全,即您是否试图将一个 int 放入该字符串列表中?使用 ArrayList 会导致它是一个不太透明的运行时错误。
  • 比使用对象更快,因为它可以避免装箱/拆箱(其中 .net 必须将值类型转换为引用类型,反之亦然)或从对象转换为所需的引用类型。
  • 允许您编写适用于具有相同底层行为的多种类型的代码,即 Dictionary<string, int> 使用与 Dictionary<DateTime, double> 相同的底层代码;使用泛型,框架团队只需编写一段代码即可实现上述两种结果。

回答by Mitchel Sellers

Generics allow you to create objects that are strongly typed, yet you don't have to define the specific type. I think the best useful example is the List and similar classes.

泛型允许您创建强类型对象,但您不必定义特定类型。我认为最有用的例子是 List 和类似的类。

Using the generic list you can have a List List List whatever you want and you can always reference the strong typing, you don't have to convert or anything like you would with a Array or standard List.

使用通用列表,您可以拥有任何您想要的列表列表列表,并且您始终可以引用强类型,您不必进行转换或任何类似于使用数组或标准列表的操作。

回答by Darren Kopp

Generics avoid the performance hit of boxing and unboxing. Basically, look at ArrayList vs List<T>. Both do the same core things, but List<T> will be a lot faster because you don't have to box to/from object.

泛型避免了装箱和拆箱的性能损失。基本上,看看 ArrayList 与 List<T>。两者都做相同的核心事情,但 List<T> 会快很多,因为你不必装箱到/从对象。

回答by Steve Landey

Generics let you use strong typing for objects and data structures that should be able to hold any object. It also eliminates tedious and expensive typecasts when retrieving objects from generic structures (boxing/unboxing).

泛型允许您对应该能够容纳任何对象的对象和数据结构使用强类型。在从通用结构(装箱/拆箱)中检索对象时,它还消除了繁琐和昂贵的类型转换。

One example that uses both is a linked list. What good would a linked list class be if it could only use object Foo? To implement a linked list that can handle any kind of object, the linked list and the nodes in a hypothetical node inner class must be generic if you want the list to contain only one type of object.

一个同时使用两者的例子是链表。如果链表类只能使用对象 Foo,它有什么好处?要实现可以处理任何类型对象的链表,如果您希望链表只包含一种类型的对象,那么链表和假设节点内部类中的节点必须是通用的。

回答by gt124

If your collection contains value types, they don't need to box/unbox to objects when inserted into the collection so your performance increases dramatically. Cool add-ons like resharper can generate more code for you, like foreach loops.

如果您的集合包含值类型,则它们在插入到集合中时不需要对对象进行装箱/拆箱,因此您的性能会显着提高。resharper 之类的酷插件可以为您生成更多代码,例如 foreach 循环。

回答by Tom Kidd

I just like them because they give you a quick way to define a custom type (as I use them anyway).

我只是喜欢它们,因为它们为您提供了一种快速定义自定义类型的方法(因为我无论如何都会使用它们)。

So for example instead of defining a structure consisting of a string and an integer, and then having to implement a whole set of objects and methods on how to access an array of those structures and so forth, you can just make a Dictionary

因此,例如,不是定义一个由字符串和整数组成的结构,然后必须实现一整套对象和方法来访问这些结构的数组等等,您只需创建一个 Dictionary

Dictionary<int, string> dictionary = new Dictionary<int, string>();

And the compiler/IDE does the rest of the heavy lifting. A Dictionary in particular lets you use the first type as a key (no repeated values).

编译器/IDE 完成其余的繁重工作。特别是 Dictionary 允许您使用第一种类型作为键(没有重复的值)。

回答by Kevin Pang

The primary advantage, as Mitchel points out, is strong-typing without needing to define multiple classes.

正如 Mitchel 所指出的,主要优点是无需定义多个类即可进行强类型化。

This way you can do stuff like:

通过这种方式,您可以执行以下操作:

List<SomeCustomClass> blah = new List<SomeCustomClass>();
blah[0].SomeCustomFunction();

Without generics, you would have to cast blah[0] to the correct type to access its functions.

如果没有泛型,您必须将 blah[0] 转换为正确的类型才能访问其功能。

回答by Kevin Pang

the jvm casts anyway... it implicitly creates code which treats the generic type as "Object" and creates casts to the desired instantiation. Java generics are just syntactic sugar.

无论如何,jvm 会进行强制转换……它隐式地创建了将泛型类型视为“对象”的代码,并创建了对所需实例化的强制转换。Java泛型只是语法糖。

回答by Chris Pietschmann

Another advantage of using Generics (especially with Collections/Lists) is you get Compile Time Type Checking. This is really useful when using a Generic List instead of a List of Objects.

使用泛型(尤其是集合/列表)的另一个优点是您可以获得编译时类型检查。这在使用通用列表而不是对象列表时非常有用。

回答by Vin

Single most reason is they provide Type safety

一个最重要的原因是他们提供类型安全

List<Customer> custCollection = new List<Customer>;

as opposed to,

相反,

object[] custCollection = new object[] { cust1, cust2 };

as a simple example.

作为一个简单的例子。