c# class 实现泛型的源码

来源:互联网 发布:中原地产 知乎 编辑:程序博客网 时间:2024/05/29 04:43
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Generic
{
    class Program
    {
        static void Main(string[] args)
        {
            MyGenericArray<int> intArray = new MyGenericArray<int>(5);
            for (int c = 0; c < 5; c++)
            {
                intArray.SetItem(c, c * 5);
            }

            for (int c = 0; c < 5; c++)
            {
                Console.Write(intArray.GetItem(c) + "");
            }

            MyGenericArray<char> charArray = new MyGenericArray<char>(5);
            for (int c = 0; c < 5; c++)
            {
                intArray.SetItem(c, (char)(c+97));
            }

            //在调用方法的时候,把泛型的类型床给方法
            intArray.GenericMethod<string>("hello Generic");
            intArray.GenericMethod<int>(100);


            for (int c = 0; c < 5; c++)
            {
                Console.Write(intArray.GetItem(c) + "");
            }

            int a, b;
            char i,j;
            a = 10;
            b = 20;
            i = 'I';
            j = 'V';

            Console.WriteLine("a:{0};b:{1}", a, b);
            Console.WriteLine("i:{0};j:{1}", i, j);
            Swap<int>(ref a, ref  b);
            Swap<char>(ref i, ref j);
            Console.WriteLine("a:{0};b:{1}", a, b);
            Console.WriteLine("i:{0};j:{1}", i, j);

            Console.ReadLine();
        }


        //ref为引用传递,在引用的过程中如果值发生变化,原来的值也会变化
        private static void Swap<T>(ref T lhs, ref T rhs)
        {
            T temp;
            temp = lhs;
            lhs = rhs;
            rhs = temp;
        }
    }


    //T可以是class,interface,instance class
    public class MyGenericArray<T> where T : struct //定义T的可以传值的类型。struct是值类型,创建一个struct类型的实例被分配在栈上。class是引用类型,创建一                                                                                                                      //个class类型实例被分配在托管堆上。
    {
        private T[] array;
        public MyGenericArray(int size)
        {
            array = new T[size + 1];
        }

        public T GetItem(int index)
        {
            return array[index];
        }

        public void SetItem(int index, T value)
        {
            array[index] = value;
        }

        
        public void GenericMethod<X>(X x)
        {
            Console.WriteLine(x.ToString());
        }
    }

    public class SubClass : MyGenericArray<int> //继承泛型class,但是强制规定了一个类型 为int类型
    {

    }

    public class SubGenericClass<T> : MyGenericArray<T> where T : struct//继承之后还是泛型
    {

    }
原创粉丝点击