1. 程式人生 > 其它 >C# 泛型玩法2

C# 泛型玩法2

技術標籤:C#

程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Test_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();
            test.Print<Dog>().Run();
            test.Print<Cat>().Run();
            //test.Print<Chook>().ChickenFlew();//報錯,因為沒實現Movement介面

            Console.ReadKey();
        }
    }

    public class Test
    {
        private Dictionary<string, object> ObjectDictionary = new Dictionary<string, object>();

        public T Print<T>() where T: class, Movement, new()
        {
            Type t = typeof(T);
            string fullName = t.FullName;
            if (ObjectDictionary.ContainsKey(fullName))
            {
                return (T)ObjectDictionary[fullName];
            }
            else
            {
                object obj = Activator.CreateInstance(t);
                ObjectDictionary.Add(fullName, obj);
                return (T)obj;
            }
        }
    }

    public interface Movement
    {
        void Run();
    }

    public class Dog : Movement
    {
        public void Run()
        {
            Console.WriteLine("狗跑了");
        }
    }

    public class Cat : Movement
    {
        public void Run()
        {
            Console.WriteLine("貓跑了");
        }
    }

    public class Chook
    {
        public void ChickenFlew()
        {
            Console.WriteLine("雞飛了");
        }
    }

}

執行:

end