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

    泛型:通过参数化类型来实现在同一份代码上操作多种数据类型。利用“参数化类型”将类型抽象化,从而实现灵活的复用。

    例子代码:

    class Program

        {

            static void Main(string[] args)

            {

                int obj = 2;

                Test<int> test = new Test<int>(obj);

                Console.WriteLine("int:" + test.obj);

                string obj2 = "hello world";

                Test<string> test1 = new Test<string>(obj2);

                Console.WriteLine("String:" + test1.obj);

                Console.Read();

            }

        }

     

        class Test<T>  // 可以用其他字母,H代替

        {

            public T obj;

            public Test(T obj)

            {

                this.obj = obj;

            }

    }

        输出结果是:

        int:2

    String:hello world

    程序分析:

    1、  Test是一个泛型类。T是要实例化的范型类型。如果T被实例化为int型,那么成员变量obj就是int型的,如果T被实例化为string型,那么obj就是string类型的。

    2、  根据不同的类型,上面的程序显示出不同的值。

    C#泛型机制:

    C#泛型能力有CLR在运行时支持:C#泛型代码在编译为IL代码和元数据时,采用特殊的占位符来表示范型类型,并用专有的IL指令支持泛型操作。而真正的泛型实例化工作以“on-demand”的方式,发生在JIT编译时。

      

  • 相关阅读:
    Kth element of Two Sorted Arrays
    Populating Next Right Pointers in Each Node I && II
    Average waiting time of SJF and Round Robin scheduling
    LRU Cache
    Calculate H-index
    Get Level of a node in a Binary Tree
    Two Sum
    Intersection of Two Linked Lists
    Symmetric Tree
    Lowest Common Ancestor of Binary (Search) Tree
  • 原文地址:https://www.cnblogs.com/wangfei1511/p/3690931.html
Copyright © 2011-2022 走看看