zoukankan      html  css  js  c++  java
  • C#泛型学习

    什么是泛型

    泛型是程序设计语言的一种特性。允许程序员在强类型程序设计语言中编写代码时定义一些可变部分,那些部分在使用前必须作出指明。各种程序设计语言和其编译器、运行环境对泛型的支持均不一样。将类型参数化以达到代码复用提高软件开发工作效率的一种数据类型。泛型类是引用类型,是堆对象,主要是引入了类型参数这个概念。

    • 比如我们需要一个方法支持传入多种类型的参数,我们可以有如下实现:
    //方法1,int参数
    public void Say(int a){
    	Console.WriteLine("Hello," + a);
    }
    //方法2,string参数
    public void Say(string b){
    	Console.WriteLine("Hello," + b);
    }
    

    这样的代码有一个问题,那就是重复的代码太多。于是我们就想到了用一个Object来接收参数。

    • 用Object来接收参数
    public void Say(object b){
    	Console.WriteLine("Hello," + b.ToString());
    }
    

    用Object来接收参数就涉及到了一个装箱和拆箱问题(引用类型和值类型的转换)

    • 最后我们使用泛型来优化
    public void Say<T>(T t){
    	Console.WriteLine("Hello," + t.ToString());
    }
    

    说明:泛型其实就是延迟声明,推迟一切可以推迟的。
    泛型在编译时才确定类型,会通过占位符来自动生成类。

    泛型缓存

    • 常规方式,就是通过全局定义一个Diction,然后Diction的键就是类型,值就是该类型对应的值,如下:
    Diction<Type,string> cache=new Diction<Type,string>();
    

    这段代码很好理解,能够保证一个类型缓存一个值。

    • 泛型缓存

    定义泛型缓存类

    public class GenericCache<T> where T : class
    {
        public static string data = string.Empty;
    
        public static string getData()
        {
            return data;
        }
    }
    

    使用

    GenericCache<string>.data = "123456";
    GenericCache<LogHelper>.data = "1234567";
    Console.WriteLine(GenericCache<string>.getData());
    Console.WriteLine(GenericCache<LogHelper>.getData());
    

    参考文章:https://blog.csdn.net/dengblog/article/details/78884995

    说明:泛型缓存效率高很多,但是只能根据类型缓存,有局限性。

    泛型约束

    我们习惯用一个T代表将要传入的类型,但是对于传入的类型却不清楚,如果让调用者任意传入类型肯定是不应该的,因此我们引入了泛型约束的概念,用于约定传入的类型必须满足某些条件才允许编译通过。

    • 值类型约束
    class ValSample<T> where T : struct{}
    

    其实我们可以看到int,char都是struct

    • 引用类型约束
    class ValSample<T> where T : class{}
    
    • 接口/基类约束
    class Sample<T> where T:Stream{}
    
    • 构造函数约束
    public T CreateInstance<T>() where T:new()
    {
         return new T();
    }
    
    • 组合约束
    class Sample<T> where T:class,IDisposable,new()
    
    class Sample<T,U> where T:struct where U:Class
    

    参考文章:https://www.cnblogs.com/haibozhu/p/6374977.html

    问题解答

    WCF、WebService为什么不支持泛型

    因为在服务发布的时候必须要确定类型。

  • 相关阅读:
    迭代和列表生成式
    python递归函数
    python函数
    变量
    python第八课后整理
    python第八课
    python第七课
    python第六课
    python第五课
    微信端/企业微信端H5页面调试方法
  • 原文地址:https://www.cnblogs.com/duanjt/p/11156668.html
Copyright © 2011-2022 走看看