泛型,它的用途和应用是什么?

编程入门 行业动态 更新时间:2024-10-25 10:28:59
本文介绍了泛型,它的用途和应用是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能存在重复: 什么是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

更多推荐

泛型,它的用途和应用是什么?

本文发布于:2023-11-25 17:25:16,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:用途   泛型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!