zoukankan      html  css  js  c++  java
  • 通过泛型参数实现接口注入

     public interface ITimeProvider
        {
            DateTime CurrentDate { get; }
        }
        public class TimeProvider : ITimeProvider
        {
            public DateTime CurrentDate { get { return DateTime.Now; } }
        }
       
        //下面实现这个Assembler
        public class Assembler
        {
            static Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>();
            static Assembler()
            {
                dictionary.Add(typeof(ITimeProvider), typeof(TimeProvider));
            }
    
            public object Creat(Type type)
            {
                if ((type == null) || !dictionary.ContainsKey(type))
                    throw new NullReferenceException();
                return Activator.CreateInstance(dictionary[type]);
            }
    
            //泛型方式调用
            public T Creat<T>()
            {
                return (T)Creat(typeof(T));
            }
        }
    
        //public class Client : IobjectWithTimeProvider
        //{
        //    public ITimeProvider TimeProvider { get; set; }
        //}
        //通过泛型参数实现接口注入 Client设计
        class Client<T> : ITimeProvider where T : ITimeProvider
        {
            public T Provider { get; set; }
            public DateTime CurrentDate
            {
                get { return Provider.CurrentDate; }
            }
        }

    测试

     /// <summary>
        ///这是 ClientTest 的测试类,旨在
        ///包含所有 ClientTest 单元测试
        ///</summary>
        [TestClass()]
        public class ClientTest
        {
    
    
          
    
            [TestMethod()]
            public void CurrentDateTest()
            {
                var client = new Client<ITimeProvider>()
                {
                    Provider = (new Assembler()).Creat<ITimeProvider>()
                };
    
            }
        }
  • 相关阅读:
    Ubuntu自启动服务脚本
    坑(一)—— Django ORM 连接超时的坑
    logging模块详解
    端口扫描之nmap命令
    端口扫描之masscan扫描
    端口扫描之Scapy模块的使用
    端口扫描之开放端口扫描方式
    Android Studio导入Project、Module的正确方法
    ImportError: No module named 'requests'
    运行python程序
  • 原文地址:https://www.cnblogs.com/wangchuang/p/2983497.html
Copyright © 2011-2022 走看看