《.NET 性能优化》—第五章 泛型

泛型是.NET Framework2.0新增的一个特性,在命名空间System.Collections.Generic,包含了几个新的基于泛型的集合类。

泛型解决了类型安全和装箱问题。
  • 类型安全: 在编译时验证对于泛型数据类型的操作,明确禁止那些可能在运行时出错的行为。
  • 在参数为object引用时,避免对值类型进行装箱。
    例如:
ArrayList emp = new ArrayList(7);
emp.add("hello");
emp.add("world");
emp.add(32);

上面的代码不仅添加了不同类型的数据作为一个列表。然而,如果使用泛型List<T>则不会出现类似的情况。泛型集合是类型安全的,不允许存储不匹配的元素,并且不会对值类型装箱。
例如,当你定义了一个List<string>, 该列表中便约束了你的数据类型,如下显示:


2789632-72b174864197c5f9.png

2789632-ae4d9c339e344b39.png
泛型约束

2789632-f34eca8f0bfdbc59.png

参考: C#泛型约束 - 雨文木可 - 博客园
泛型的使用有系统自定义的一些泛型类型,泛型方法,泛型委托等,也可以自定义泛型的使用。

Demo

以下做了一个小Demo,分别是泛型类下使用泛型方法和非泛型方法, 非泛型类下使用非泛型方法和泛型方法。
Code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericTest
{
    class Program
    {
        static void Main(string[] args)
        {
            GenericClass<int> class1 = new GenericClass<int>();
            class1.Say();
            class1.Say(8);

            GenericClass2 class2 = new GenericClass2();
            class2.Say();
            class2.Say<int>(8);

            Console.ReadLine();

        }
    }

}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GenericTest
{
    public class GenericClass<T>
    {
        public void Say()
        {
            // do nothing
        }

        public void Say(T t1)
        {
            Console.WriteLine($"{t1}");
        }
    }

    public class GenericClass2
    {
        public void Say()
        {
            // do nothing
        }

        public void Say<T>(T t1)
        {
            Console.WriteLine($"{t1}");
        }
    }
}

Result:


2789632-52a6c06963324613.png

2789632-4d77039bb2409e81.png

2789632-f7a4928d51a8bfd0.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值