zoukankan      html  css  js  c++  java
  • 泛型

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace 泛型
    {
        class Program
        {
            static void Main(string[] args)
            {
                //普通写法
                showPutIn(445);
                showPutIn("happy");
                long s = 999999;
                showPutIn(s);
                //完整写法
                showPutIn<string>("I'm a string");
                //         <T>      (T parm)
    
                //类对象初始化器
                sunA AA = new sunA() { age = 99, name = "hi", hight = 99.9 };
    
                //把 Parent 子类 sunA 的实例 AA 传入泛型参数
                whoRU(AA);
            }
            // T 是一个类型参数,只有在函数被调用时才能确定
            // 没有类型的转换过程,比用object装箱拆箱效率高
            static void showPutIn<T>(T parm)
            {
                Console.WriteLine("{0} is {1}", parm, parm.GetType());
            }
    
            //泛型约束
            //不约束时,SUN可以是任何类型,且parm里只有object的方法
            //通过where SUN : Parent约束后,则只能传入Parent或Parent的子类
            //并且SUN有了Parent的方法和属性
            static void whoRU<SUN>(SUN parm) where SUN : Parent
            {
                parm.name = "haha";
            }
        }
    
        class Parent
        {
            public string name;
            public int age;
            public double hight;
        }
        class sunA : Parent { }
        class sunB : Parent { }
    }
    

      

  • 相关阅读:
    NoInstall_Mysql
    说话
    我是一名博客新人
    pom.xml报错
    模板——链表模板、有序链表模板及测试
    模板——函数模板
    模板——类模板
    MDI程序演示
    容器和算法2 C++快速入门48(完)
    MDI程序演示
  • 原文地址:https://www.cnblogs.com/Jeely/p/11003494.html
Copyright © 2011-2022 走看看