C# 反射与工厂模式

请添加图片描述

1.接口

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

namespace DataBase.Interface
{

    // 数据库 接口
    public interface IDBInterface
    {
        // 查询方法
        void Query();
    }
}

2.SQL数据库(类库 DataBase.Sql.dll)

using DataBase.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBase.Sql
{
    // SQl类
    public class SqlServerHelper : IDBInterface
    {
        public SqlServerHelper()
        {
            Console.WriteLine($"{this.GetType().Name} 被构造");
        }

        // 接口继承
        public void Query()
        {
            Console.WriteLine($"{this.GetType().Name}.Query");
        }
    }
}

3.Mysql数据库(DataBase.Mysql.dll)

using DataBase.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataBase.Mysql
{
    // Mysql 数据库 
    public class MySqlHelper : IDBInterface
    {
        // 构造函数
        public MySqlHelper()
        {
            Console.WriteLine($"{this.GetType().Name} 被构造");
        }

        // 查询
        public void Query()
        {
            Console.WriteLine($"{this.GetType().Name}.Query");
        }
    }
}

4.工厂类(读取配置文件)

配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
	<appSettings>
		<add key="IDBHelperConfig" value="DataBase.Sql.SqlServerHelper, DataBase.Sql"/>
	</appSettings>
</configuration>
using DataBase.Interface;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionFactory
{
    public class Factory
    {
        // 读取配置文件
        public static string IDBHelperConfig = ConfigurationManager.AppSettings["IDBHelperConfig"];

        // Dll 文件名
        private static string DllName = IDBHelperConfig.Split(',')[1];

        // 反射 类名
        private static string TypeName = IDBHelperConfig.Split(',')[0];

        // 工厂创建函数
        public static IDBInterface CreateHelper()
        {
            Console.WriteLine("加载DLL:" + DllName);
            // 反射加载Dll程序集
            Assembly assembly = Assembly.Load(DllName);

            Console.WriteLine($"获取类: {TypeName}");

            // 获取类的 Type
            Type typeHelper = assembly.GetType(TypeName);

            // 创建对象
            object oHelper = Activator.CreateInstance(typeHelper);

            // 类型转换为 接口类型
            IDBInterface iDbHelper = (IDBInterface)oHelper;
            return iDbHelper;
        }
    }
}

5.调用测试

using DataBase.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionFactory
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 反射与工厂模式
            Console.WriteLine("-----反射与工厂模式----------");

            // 使用工厂模式创建 对象(接口)
            IDBInterface iDBInterface = Factory.CreateHelper();

            Console.WriteLine("-----调用对象函数----------");
            // 调用对象函数
            iDBInterface.Query();

            #endregion
            Console.ReadLine();
        }
    }
}

结果

SQL

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
	<appSettings>
		<add key="IDBHelperConfig" value="DataBase.Sql.SqlServerHelper, DataBase.Sql"/>
	</appSettings>
</configuration>

在这里插入图片描述

Mysql

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
	<appSettings>
		<add key="IDBHelperConfig" value="DataBase.Mysql.MySqlHelper, DataBase.Mysql"/>
	</appSettings>
</configuration>

在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C# 反射是指在运行时动态地获取类的信息,通过反射可以获取类的属性、方法、事件等信息,以及动态创建对象、调用方法、获取值等操作。这使得我们能够在运行时动态地编写代码,可以写出更加灵活和可扩展的程序。 C# 反射的核心是 `System.Reflection` 命名空间,该命名空间包含了许多与反射相关的类和接口,比如 `Type` 类、`MethodInfo` 类、`PropertyInfo` 类等。 下面是一些常用的反射操作: 1. 获取类型信息 可以使用 `typeof` 关键字或者 `Type.GetType()` 方法来获取类型的信息。`typeof` 关键字用于获取编译时已知的类型信息,而 `Type.GetType()` 方法则可以通过类型名称获取运行时的类型信息。 ```csharp // 获取 System.String 类型的信息 Type type1 = typeof(System.String); // 获取指定类型名称的信息 Type type2 = Type.GetType("System.String"); ``` 2. 获取成员信息 可以使用 `Type.GetMembers()` 方法获取类型的所有成员信息,包括属性、方法、字段、事件等。也可以使用 `Type.GetMethod()`、`Type.GetProperty()`、`Type.GetField()`、`Type.GetEvent()` 等方法获取指定成员的信息。 ```csharp Type type = typeof(Person); // 获取类型的所有成员信息 MemberInfo[] members = type.GetMembers(); // 获取指定属性的信息 PropertyInfo property = type.GetProperty("Name"); // 获取指定方法的信息 MethodInfo method = type.GetMethod("SayHello"); // 获取指定字段的信息 FieldInfo field = type.GetField("Age"); // 获取指定事件的信息 EventInfo eventInfo = type.GetEvent("PropertyChanged"); ``` 3. 动态创建对象 可以使用 `Activator.CreateInstance()` 方法动态创建对象,也可以使用 `Type.InvokeMember()` 方法调用构造函数来创建对象。 ```csharp Type type = typeof(Person); // 使用 Activator.CreateInstance() 方法创建对象 Person person1 = (Person)Activator.CreateInstance(type); // 使用 Type.InvokeMember() 方法调用构造函数创建对象 Person person2 = (Person)type.InvokeMember(null, BindingFlags.CreateInstance, null, null, new object[] { "Tom", 18 }); ``` 4. 调用成员 可以使用 `MethodInfo.Invoke()` 方法调用方法,也可以使用 `PropertyInfo.SetValue()` 方法设置属性的值,使用 `FieldInfo.SetValue()` 方法设置字段的值。 ```csharp Type type = typeof(Person); Person person = new Person("Tom", 18); // 调用方法 MethodInfo method = type.GetMethod("SayHello"); method.Invoke(person, null); // 设置属性的值 PropertyInfo property = type.GetProperty("Name"); property.SetValue(person, "Jerry", null); // 设置字段的值 FieldInfo field = type.GetField("Age"); field.SetValue(person, 20); ``` 以上是 C# 反射的一些基本操作,反射的应用非常广泛,可以用来实现插件式开发、ORM 映射等功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

廷益--飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值