为什么泛型称为泛型? [英] Why are generics called generics?

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

问题描述

冒着成为村里白痴的风险,有人可以向我解释为什么泛型被称为泛型?我了解它们的用法和优点,但如果通用定义是一般且泛型集合是类型安全,那么为什么这不是一个误称?



例如,一个ArrayList可以容纳任何对象:

  ArrayList myObjects = new ArrayList(); 
myObjects.Add(one);
myObjects.Add(1);

而字符串类型的泛型集合只能保存字符串:

  var myStrings = new List< string>(); 
myStrings.Add(one);
myStrings.Add(1);

我只是不清楚为什么它被称为通用。如果答案是......这使得可以设计延迟一种或多种类型规范的类和方法,直到类或方法被客户端代码声明和实例化为止。从这里,那么我想这是有道理的。也许我有这种心理失误,因为我只是在Java引入泛型后才开始编程,所以我不记得有一段时间。但仍然...



任何帮助表示感谢。 Generic正在谈论实施。您可以编写一个适用于任何类型的Generic列表实现,而不必为每个要使用的类型编写特定的实现。


At the risk of becoming the village idiot, can someone explain to me why generics are called generics? I understand their usage and benefits, but if the definition of generic is "general" and generic collections are type safe, then why isn't this a misnomer?

For example, an ArrayList can hold anything that's an object:

ArrayList myObjects = new ArrayList();
myObjects.Add("one");
myObjects.Add(1);

while a generic collection of type string can only hold strings:

var myStrings = new List<string>();
myStrings.Add("one");
myStrings.Add("1");

I'm just not clear on why it's called "generic". If the answer is "...which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code." from here, then I suppose that makes sense. Perhaps I'm having this mental lapse because I only began programming after Java introduced generics, so I don't recall a time before them. But still...

Any help is appreciated.

解决方案

"Generic" is talking about the implementation. You write a single "Generic" list implementation that works with any type, instead of having to write specific implementations for each type you want to use.

这篇关于为什么泛型称为泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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