美文网首页
C#笔记-反射

C#笔记-反射

作者: AiDede | 来源:发表于2017-10-19 16:32 被阅读39次

    我们平常调用一个类库的方式,通常为添加引用的方式

    • 我们新建一个解决方案,新建一个项目Reflection,然后新建一个DBUtil类库
    • 在Reflection中的Progame.cs中添加几行代码
    namespace Reflection
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("");
                //Code
                Console.ReadLine();
            }
        }
    }
    
    • 在DBUtil类库中,新建一个类SQLHelper
    namespace DBUtil
    {
        public class SqlHelper
        {
            public SqlHelper() {
                Console.WriteLine("这里是SqlHelper的构造方法");
            }
            public void Query() {
                Console.WriteLine("SqlHelper的查询方法");
            }
        }
    }
    
    • 如果我们需要调用这个SqlHelper类,我们通常在Reflection项目中,添加DBUtil的引用



    • 然后我们可以在代码中调用我们的SqlHelper

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using DBUtil;//添加命名空间
    namespace Reflection
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("");
    
                SqlHelper oSqlHelper = new SqlHelper();
                oSqlHelper.Query();
    
                Console.ReadLine();
            }
        }
    }
    
    运行结果
    • 我们现在通过引用来加载我们的其他类库,这样就要求我们在程序开发期间就要将类库的引用写死,如果我们的程序要求我们能够动态的引用DLLL,我们怎么办呢,这个时候,我们就有了反射这个概念

    通过反射可以动态的调用我们的DLL

    • 我们先把我们调用部分的代码删掉,然后把引用关系删掉
    • 我们先编译生成一下我们的DBUtil项目,然后在该项目的bin/Debug文件夹下找到我们的DBUtil.dll,复制到Reflection文件夹下的bin/Debug下


    • 然后我们在Program.cs代码中,首先引入System.Reflection
    using System.Reflection;
    
    • 然后我们可以通过AssemblyLoad方法加载我们的dll文件
                Assembly assembly = Assembly.Load("DBUtil");//动态加载Dll
    

    相关文章

      网友评论

          本文标题:C#笔记-反射

          本文链接:https://www.haomeiwen.com/subject/lxzyuxtx.html