泛型有什么好处,为什么要使用它们? [英] What is cool about generics, why use them?

查看:34
本文介绍了泛型有什么好处,为什么要使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

  • 允许您编写代码/使用类型安全的库方法,即列表<字符串>保证是一个字符串列表.
  • 由于使用了泛型,编译器可以对代码执行编译时检查以确保类型安全,即您是否尝试将 int 放入该字符串列表中?使用 ArrayList 会导致运行时错误不那么透明.
  • 比使用对象更快,因为它可以避免装箱/拆箱(其中 .net 必须转换 值类型到引用类型,反之亦然)或从对象转换为所需的引用类型.
  • 允许您编写适用于具有相同底层行为的多种类型的代码,即字典使用与 Dictionary 相同的底层代码;使用泛型,框架团队只需编写一段代码即可实现上述两种结果,同时具有上述优势.
    • 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.
    • 这篇关于泛型有什么好处,为什么要使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆