C# 泛型 介面約束

iamzxf發表於2015-05-06


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

namespace interfaceConstraint
{
    interface IPhoneNumber
    {
        String Name
        {
            get;
            set;
        }

        string Number
        {
            get;
            set;
        }
    }

    class Friend : IPhoneNumber
    {
        string name;
        string number;

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

        public string Number
        {
            get { return name; }
            set { name = value; }
        }

        public Friend(string name, string number)
        {
            this.name = name;
            this.number = number;
        }
    }

    class Supplier : IPhoneNumber
    { 
        string name;
        string number;

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

        public string Number
        {
            get { return name; }
            set { name = value; }
        }

        public Supplier(string name, string number)
        {
            this.name = name;
            this.number = number;
        }
    }

    class others
    { }


    class PhoneList<T> where T : IPhoneNumber
    {
        T[] phList;
        int end;
        public PhoneList()
        { 
            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<Friend> phList1 = new PhoneList<Friend>();

            phList1.Add(new Friend("zhangsan", "123")); 
            phList1.Add(new Friend("lisi", "234"));
            phList1.findByName("lisi");
            Console.WriteLine("============");

            PhoneList<Supplier> phList2 = new PhoneList<Supplier>();

            phList1.Add(new Friend("zhangsan1", "123"));
            phList1.Add(new Friend("lisi1", "234"));
            phList1.findByName("lisi11");

            Console.ReadLine();
        }
    }
}


相關文章