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>()
                };
    
            }
        }
  • 相关阅读:
    gulp之gulp-md5模块
    PCA调试--https证书问题
    linux开机启动tomcat
    sqlserver查看过滤存储过程内容
    oracle case when
    springboot1 缓存静态文件
    mysql修改联合主键
    git命令行获取某分支代码
    IDEA查看项目对应的git地址
    IDEA 中tomcat日志位置
  • 原文地址:https://www.cnblogs.com/wangchuang/p/2983497.html
Copyright © 2011-2022 走看看