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

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    
    namespace codeTest
    {
        class Program
        {
            //委托泛型的使用
            delegate T ShowNum<T>(T n);
    
            static int Show(int num)
            {
                return num;
            }
    
            static void Main(string[] args)
            {
                //MyGeneric<int,int> myGenericInt = new MyGeneric<int,int>(5);
                //SubClass myGenericInt = new SubClass(5);
                SubClass2<int, int> myGenericInt = new SubClass2<int, int>(5);
                for (int i = 0; i < myGenericInt.arry.Length; i++)
                {
                    myGenericInt.SetArryValue(i, i);
                }
                for (int i = 0; i < myGenericInt.arry.Length; i++)
                {
                    Console.WriteLine(myGenericInt.GetArryValue(i));
                }
    
                string a = "11", b = "22";
                Console.WriteLine("a is {0},b is {1}", a, b);
                swap<string>(ref a, ref b);
                Console.WriteLine("a is {0},b is {1}",a,b);
    
    
                ShowNum<int> dele = new ShowNum<int>(Show);
                Console.WriteLine(string.Format("Show num is {0}", dele(10)));
    
                Console.ReadLine();
            }
    
            //在方法上实现泛型
            static void swap<T>(ref T a, ref T b) where T : class
            {
                T tmp;
                tmp = a;
                a = b;
                b = tmp;
            }
        }
    
        //在类上实现泛型
        class MyGeneric<T, K> where T : struct
        {
            //where T:class  引用类型
            //where T:struct 值类型
            //where T:interface 接口
            //where T:具体的基类 
            public T[] arry;
            public MyGeneric(int index)
            {
                arry = new T[index];
            }
    
            public T GetArryValue(int index)
            {
                return arry[index];
            }
    
            public void SetArryValue(int index, T value)
            {
                arry[index] = value;
            }
        }
    
        //继承泛型时指定类型后,基类不再是泛型
        class SubClass : MyGeneric<int, int>
        {
            public SubClass(int num)
                : base(num)
            {
            }
        }
    
    
        class SubClass2<T, K> : MyGeneric<T, K> where T : struct
        {
            public SubClass2(int num)
                : base(num)
            {
            }
        }
    }
  • 相关阅读:
    web版ssh的使用
    Django高级篇三。restful的解析器,认证组件,权限组件
    Django中的缓存(内存,文件,redis)
    Python使用redis
    跨域请求
    python发送邮箱
    登录服务器失败 IP 统计和处理方法
    centos中单进程监控
    编译搭建lnmp+zabbix
    Django+Uwsgi+Nginx项目部署文档
  • 原文地址:https://www.cnblogs.com/lgxlsm/p/4772108.html
Copyright © 2011-2022 走看看