zoukankan      html  css  js  c++  java
  • 反射

    System.Reflection.Assembly ass;
        Type type ;
       object obj;
       try
       {
        ass = System.Reflection.Assembly.LoadFile(@"d:\TestReflect.dll");
        type = ass.GetType("Webtest.ReflectTest");//必须使用名称空间+类名称
        System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称
        obj = ass.CreateInstance("Webtest.ReflectTest");//必须使用名称空间+类名称
        string s = (string)method.Invoke(obj,new string[]{"jianglijun"}); //实例方法的调用
       
        Response.Write(s+"<br>");
        method = type.GetMethod("WriteName");//方法的名称
        s = (string)method.Invoke(null,new string[]{"jianglijun"}); //静态方法的调用
        Response.Write(s+"<br>");
    
        method = type.GetMethod("WriteNoPara");//无参数的实例方法
        s = (string)method.Invoke(obj,null);
        Response.Write(s+"<br>");
        method = null;
       }
       catch(Exception ex)
       {
        Response.Write(ex+"<br>");
       }
       finally
       {
        ass = null;
        type = null;
        obj = null;
       }
    
    

    关于反射:
    反射:即获得元数据的信息。
    Typeof 获得数据类型;MethodInfo获得方法的信息。
    实例1 加载外部的dll文件,并通过反射来调用程序集中的类方法和属性

    1.1 创建一个类

    using System;
    
    namespace Webtest
    {
     public class ReflectTest
     {
      public ReflectTest()
      {}
    
      public string WriteString(string s)
      {
       return "欢迎您," + s;
      }
    
      public static string WriteName(string s)
      {
       return "欢迎您光临," + s;
      }
    
      public string WriteNoPara()
      {
       return "您使用的是无参数方法";
      }
     }
    }
    
    

    通过反射进行方法调用

    实例2 通过反射调用当前同一个程序集的类方法和属性

     XmlDocument dom = new XmlDocument();
                    dom.LoadXml("<Items></Items>");
    
                    String sMethod = Page.Request.QueryString["method"];
                    FileUtilitity fileUtil = new FileUtilitity();
                    Ticket[] Tickets;
                    XmlElement root = dom.DocumentElement;
    
                    //Tickets = fileOper.ReadFile();
                    Type type = fileUtil.GetType();
                    System.Reflection.MethodInfo method = type.GetMethod(sMethod);
                    Tickets = (Ticket[])method.Invoke(fileUtil, null);
    
                    foreach (Ticket tmpTicket in Tickets)
                    {
                        GetXmlFragmentString(tmpTicket, root, dom);
                    }
                    string innerXml = dom.InnerXml;
                    Response.Write(innerXml);
    

    此实例完整的代码可参考txt文件的操作篇。

    应用场景

    反射常用在工厂模式中。比如一个应用程序的后台数据库为ACCESS、MS SQL和Oracle。我们根据configure.xml中的配置类创建不用的访问数据库实例。

  • 相关阅读:
    分享一个关于Cookie做的实验结果
    使用jest进行单元测试
    【转载】为什么单反镜头做不小,镜头越好越重呢?
    【转载】解读手机摄像头
    【转载】2019中国机器视觉产业全景图谱
    【行业】视觉传感器
    图像质量测评
    COM口了解下
    dbus-python的API及示例
    QtDbus的API及示例
  • 原文地址:https://www.cnblogs.com/mingle/p/csharp_reflect.html
Copyright © 2011-2022 走看看