泛型

来源:互联网 发布:c语言可视化软件 编辑:程序博客网 时间:2024/06/07 06:44

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace MyConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            // 测试范型集合
            List<Person> plist = new List<Person>();
            plist.Add(new Person("A", 10, Genders.Male));
            plist.Add(new Person("B", 13, Genders.Male));
            plist.Add(new Person("C", 20, Genders.Female));
            plist.Add(new Person("D", 45, Genders.Male));
           
            foreach (Person p in plist)
            {
                Console.WriteLine("{0}-{1}-{2}", p.Name, p.Age, p.Gender);
            }

            Dictionary<string, Person> pdic = new Dictionary<string, Person>();
            foreach (Person p in plist)
            {
                pdic.Add(p.Name, p);
            }

            foreach (Person p in plist)
            {
                Console.WriteLine("{0}-{1}-{2}", p.Name, p.Age, p.Gender);
            }

            /////////////////////////////////////////////////////////////////////
            // 范型类型
            int a = 1, b = 2;
            Swap<int>(ref a, ref b);
            Console.WriteLine("a={0}, b={1}", a, b);

            long al = 1, bl = 2;
            Swap<long>(ref al, ref bl);

            GClass<int> gc = new GClass<int>(100);
            gc.PrintString();

            // 范型接口限定
            KingTDoc ktd = new KingTDoc();
            MyGeneric<KingTDoc> gktd = new MyGeneric<KingTDoc>();
            gktd.PrintTitle(ktd);

            Console.Read();
        }

        /// <summary>
        /// 范型方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="x"></param>
        /// <param name="y"></param>
        static void Swap<T> (ref T x, ref T y) 
        { 
            T temp = x; 
            x = y; 
            y = temp; 
        } 
    }


    // 范型类型
    public class GClass<T>
    {
        private T t;
        public GClass(T v)
        {
            t = v;
        }

        public void PrintString()
        {
            Console.WriteLine(t.ToString());
        }
    }


    ////////////////////////////////////////////
    // 限定接口的类型
   
    // 先定义一个interface 
    public interface IDocument 
    { 
        string Title {get;} 
        string Content {get;} 
    } 

    // 让范型类T实现这个interface 
    public class MyGeneric<T> where T : IDocument
    {
        public void PrintTitle(T v)
        {
            Console.WriteLine(v.Title);
        }
    }

    public class KingTDoc : IDocument
    {

        #region IDocument 成员

        public string Title
        {
            get
            {
                return "KingTDoc_Title";
            }
        }

        public string Content
        {
            get
            {
                return "KingTDoc_Content";
            }
        }

        #endregion
    }
}