Features of Generics
- It helps you in code reuse, performance and type safety.
- You can create your own generic classes, methods, interfaces and delegates.
- You can create generic collection classes. The .NET framework class library contains many new generic collection classes in System.Collections.Generic namespace.
- You can get information on the types used in generic data type at run-time.
Advantages of Generics
-
可重用性: 您可以在同一代码中将单个泛型类型定义用于多种用途,而无需进行任何更改。 例如,您可以创建一个泛型方法来添加两个数字。 此方法可用于添加两个整数和两个浮点数,无需对代码进行任何修改.
-
类型安全性: 泛型数据类型提供更好的类型安全性,尤其是在集合的情况下。 使用泛型时,您需要定义要传递给集合的对象类型。 这有助于编译器确保只有定义中定义的那些对象类型才能传递给集合.
-
性能: 与普通系统类型相比,泛型类型提供了更好的性能,因为它们减少了对变量或对象的装箱、拆箱和类型转换的需要。