C# 泛型 基類約束

iamzxf發表於2015-05-06

基類約束,要求型別引數只能是基類或者由基類派生的類。

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

namespace classConstraint
{
    class PhoneNumber
    {
        string name;
        string number;

        public String Name
        {
            get { return name; }
            set { name = value; }
        }

        public String Number
        {
            get { return number; }
            set { number = value; }
        }
        public PhoneNumber(string name, string phoneNumber)
        {
            this.name = name;
            this.number = phoneNumber;
        }
    }

    class FriendNumber : PhoneNumber
    {
        bool isWorkNumber;
        public bool IsWorkNumber
        {
            get { return isWorkNumber; }
            set { isWorkNumber = value; }
        }

        public FriendNumber(string name, string number, bool isWorkNumber)
            : base(name, number)
        {
            this.isWorkNumber = isWorkNumber;
        }
    }

    class Supplier : PhoneNumber
    {
        public Supplier(string name, string number)
            : base(name, number)
        { }
    }

    class others
    { }

    class PhoneList<T> where T: PhoneNumber
    {
        T[] phList;
        int end;

        public PhoneList()
        {
            this.phList = new T[10];
            end = 0;
        }

        public bool Add(T newNumber)
        {
            if (end == 10)
                return false;

            phList[end] = newNumber;
            end++;
            return true;
        }

        public void findByName(string name)
        {
            for (int i = 0; i < end; i++)
            {
                if (phList[i].Name == name)
                {
                    Console.WriteLine("找到了,{0}的聯絡電話是{1}",name,phList[i].Number);
                    return;
                }
            }

            Console.WriteLine("沒有找到!");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {

            PhoneList<FriendNumber> plist = new PhoneList<FriendNumber>();
            plist.Add(new FriendNumber("zhangsan", "23",true));
            plist.Add(new FriendNumber("lisi", "6691182", true));
            plist.Add(new FriendNumber("wangwu", "23423", false));

            plist.findByName("lisi");
            Console.WriteLine("================");

            PhoneList<Supplier> plist2 = new PhoneList<Supplier>();
            plist2.Add(new Supplier("iphone", "123"));
            plist2.Add(new Supplier("android", "123"));
            plist2.findByName("windowsPhone");

           
            PhoneList<PhoneNumber> plist3 = new PhoneList<PhoneNumber>();
           // PhoneList<others> plist4 = new PhoneList<others>();
            Console.ReadLine();
        }
    }
}


相關文章