可能存在重复: 什么是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 expectedAs 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
更多推荐
泛型,它的用途和应用是什么?
发布评论