• 关于反射的疑惑


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

    疑惑:既然知道了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进行实例化,进而操作对象的一种机制(自己理解)。

  • 相关阅读:
    Python基础5_字典,集合
    Python基础3_基本数据类型,字符串,for循环
    Python基础2_while循环,格式化输出,基本运算符,编码,
    Python基础1_初识,注释,变量,if语句
    编写高质量代码[读书笔记]
    php地方天气
    [head first php&mysql]读书笔记-基本的安全信息(第五章)
    上传本地图片
    检测IE
    underscore源码解析(实用的功能)
  • 原文地址:https://www.cnblogs.com/zjBoy/p/2612916.html
Copyright © 2020-2023  润新知