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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhonghua_csdn/article/details/90653006

泛型是.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

猜你喜欢

转载自blog.csdn.net/zhonghua_csdn/article/details/90653006