反射创建对象,反射+简单工厂+配置文件

创建一个控制台应用程序写反射+简单工厂+配置文件

目录如下

步骤一:定义接口

namespace Interface

{
    /// <summary>
    /// 数据访问类抽象
    /// </summary>
    public interface IDBHelper
    {
        void Query();
      
    }

}

步骤二:定义SqlServerHelper类继承IDBHelper接口

using Interface;
using System;


namespace Helper
{
    /// <summary>
    /// SqlServerHelper类
    /// </summary>
    public class SqlServerHelper : IDBHelper
    {
        //private static string ConnectionStringCustomers = ConfigurationManager.ConnectionStrings["Customers"].ConnectionString;
        public void Query()
        {
            Console.WriteLine("{0}.Query", this.GetType().Name);
        }
        public SqlServerHelper()
        {
            Console.WriteLine("{0}被构造", this.GetType().Name);
        }
    }

}

步骤三:在配置文件App.config中添加

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

        ....

 <!--配置-->
  <appSettings>
    <add key="IDBHelperConfig" value="Helper,Helper.SqlServerHelper"/>

  </appSettings>

</configuration>

步骤四:创建简单工厂SimpleFactory

using Interface;
using System;
using System.Configuration;
using System.Reflection;
namespace Factory
{
    /// <summary>
    /// 简单工厂
    /// </summary>
    public class SimpleFactory
    {
        /// <summary>
        /// 字符串放在配置文件App.config中
        /// </summary>
private static string IDBHelperConfig = ConfigurationManager.AppSettings["IDBHelperConfig"];//AppSettings["key"]
        private static string DllName = IDBHelperConfig.Split(',')[0];//dll
        private static string TypeName = IDBHelperConfig.Split(',')[1];//type


        public static IDBHelper CreateDBHelper()
        {
            //1.加载dll
            Assembly assembly = Assembly.Load(DllName);            
            //2.获取类型信息
            Type type = assembly.GetType(TypeName);
            //3.创建对象
            object oHelper = Activator.CreateInstance(type);
            //4.类型转换
            IDBHelper dBHelper = (IDBHelper)oHelper;
            //5.调用方法           
            return dBHelper;
        }
    }

}

步骤五:完成Program.cs

static void Main(string[] args)
        {
           
            try

 #region 反射+工厂+Config配置
                {
                    //IOC 可配置,可扩展
                    Console.WriteLine("************反射+工厂+Config配置************");
                    IDBHelper dBHelper = SimpleFactory.CreateDBHelper();
                    dBHelper.Query();
                }

    #endregion

 }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.Read();

        }

大公告成!!!看看最后的效果


喜欢的可以自己去试试哦!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

满天心

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值