码迷,mamicode.com
首页 > Windows程序 > 详细

C#泛型

时间:2015-08-31 06:27:39      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

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)
        {
        }
    }
}

 

C#泛型

标签:

原文地址:http://www.cnblogs.com/lgxlsm/p/4772108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!