泛型,它的用途和应用是什么? [英] What is generics, its uses and application?

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

问题描述


可能存在重复:

什么是C# ?


泛型的用途以及何时可以使用?泛型用于创建类型安全集合,如List,Map等。它意味着我们只能添加已知/期望的类型到集合,以避免在一个集合中存储不同的数据。例如

  //没有泛型
ArrayList list = new ArrayList();
list.add(new Object());
list.add(new Interger());
list.add(new String());

//带泛型
ArrayList< String> list = new ArrayList< String>();
list.add(new Object()); //编译时错误
list.add(new Interger()); //编译时错误
list.add(new String()); //确定字符串的期望值

正如您从上面看到的,代码泛型已经被引入来创建类型安全因此我们不会在运行时从集合中获得一些意想不到的对象类型。



除了集合,我们还可以将泛型应用于方法和类。 b

Possible Duplicate:
What is generics in C#?

What are the uses of generics and when can it be used?

解决方案

Generics is used to create "Type safe" collections like List, Map etc. It means that we can add only known/expected types to collections in order to avoid storing different data in one collection. For e.g

//without generics
ArrayList list = new ArrayList();
list.add(new Object());
list.add(new Interger());
list.add(new String());

//with generics 
ArrayList<String> list = new ArrayList<String>();
list.add(new Object()); //compile time error
list.add(new Interger()); //compile time error
list.add(new String()); //ok string its expected

As you can see from above code generics have been introduced to create type safe collections so that we wont get some unexpected type of object from collections at runtime.

Apart from collections we can also apply generics to methods and classes

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

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