关于反射的疑惑

自己在刚接触反射的时候,遇到了一个疑惑,在网上查了查,好多人遇到了和我一样的问题。

疑惑:既然知道了Dll文件,为什么不直接添加引用然后通过new 产生对象,相反却采用反射机制?

先上代码:

//-------------简单的一个类库,里面只有一个类文件------------//

using System;

using System.Collections.Generic;

using System.Text;

 

namespace myReflect

{

    public class student

    {

        public string getStudentInfo(string name)

        {

            return "Hello,I'm " + name;

        }

    }

}

//-------------------测试反射(用的是winform)--------------------------//

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Reflection;

 

namespace 反射

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            string path = @"C:\Users\Change\Documents\Visual Studio 2005\Projects\字符串公式匹配\student\bin\Debug\student.dll";

            string className = "myReflect.student";

            string method = "getStudentInfo";

 

            testReflect(path,className,method);

        }

        /// <summary>

        ///

        /// </summary>

        /// /// <param name="classPath">路径要用全路径</param>

        /// <param name="className">(命名空间+类名)</param>

        /// <param name="method">方法</param>

        void testReflect(string classPath,string className,string meth)

        {

            System.Reflection.Assembly ass;

            Type type ;

            object obj;

 

            ass = System.Reflection.Assembly.LoadFile(classPath);

            type = ass.GetType(className);//必须使用名称空间+类名称

            System.Reflection.MethodInfo method = type.GetMethod(meth);//方法的名称

            obj = ass.CreateInstance(className);//必须使用名称空间+类名称

           

            string s = (string)method.Invoke(obj,new string[]{"ZJ"}); //实例方法的调用

            MessageBox.Show(s);

        }

    }

}

结果:

Hello,I'm ZJ

解释:

首先,反射引用的时候,不一定要添加引用,只要给一个绝对路径就可以了。

其次,你不知道命名空间.类名,你知道的仅仅是形参,无法用形参进行实例化对象的。

综合以上两点可知 反射是一种动态调用dll进行实例化,进而操作对象的一种机制(自己理解)。

原文地址:https://www.cnblogs.com/zjBoy/p/2612916.html