C# 程序集和反射详解

2019-12-30 15:49:33于海丽

C#,程序集,反射


      SqlServerHelper _SqlServerHelper = new SqlServerHelper(1);
      bool result = typeof(SqlServerHelper).IsSubclassOf(typeof(BaseSql));
      Console.WriteLine(result);

C#,程序集,反射

项目中常用的利用反射来动态切换数据库Demo:

新建类库项目My.Sql.IDal,并添加接口ISqlHelper。通过接口来实现数据库操作的类的解耦,因为接口是抽象的。


  public interface ISqlHelper
  {
    string Query();
  }

添加类库项目My.MySql.Dal,并新增类MySqlHelper.cs

My.Sqlserver.Dal、My.MySql.Dal项目分别添加对项目My.Sql.IDal的引用。让SqlServerHelper继承自接口ISqlHelper


public class MySqlHelper : ISqlHelper
  {
    public string Query()
    {
       return this.GetType().ToString();
    }
  }
  public class SqlServerHelper :ISqlHelper
  {
    private int age = 16;
    public string Name { get; set; }
    public string Query()
    {
      return this.GetType().ToString();
    }
  }

添加App.config配置项


 <appSettings>
  <add key="DBName" value="My.Sqlserver.Dal,SqlServerHelper"/>
 </appSettings>

ReflectedDemo项目中Program.cs调用代码:


string str = ConfigurationManager.AppSettings["DBName"];
      string strAssembly = str.Split(',')[0];
      string strClass=str.Split(',')[1];
      Assembly assembly = Assembly.Load(strAssembly);
      Type t = assembly.GetType(strAssembly + "." + strClass);
      ISqlHelper obj = Activator.CreateInstance(t) as ISqlHelper;
      Console.WriteLine(obj.Query());

C#,程序集,反射

这样每次需要切换数据库时,只要修改配置文件就可以了。

项目结构:

C#,程序集,反射

注意:反射虽然很强大,但却是比较耗性能的,所以一般和缓存结合起来使用。

项目源码:ReflectedDemo.zip

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持ASPKU!


注:相关教程知识阅读请移步到c#教程频道。