zoukankan      html  css  js  c++  java
  • .NET反射应用

         .Net中,在编写框架时,反射是最长用的一个知识点,在这举个小例子,旨在说明反射如何应用;本文只程序中只涉及到System.Type的应用,通过这个类可以访问关于任何数据类型的信息,注释部分涉及到System.Reflection.Assembly类,该类用于访问给定程序集的相关信息,或者把这个程序集加载到程序中。
    示例代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Reflection;
    
    namespace ConsoleReflect
    {
        class Program
        {
            static void Main(string[] args)
            {
                ///对类库的调用,不详解
                //Assembly assmbly = Assembly.LoadFile("类库目录");
                //Type[] lstType = assmbly.GetExportedTypes();
                List<Type> lstType = new List<Type>();
                string a = new Program().GetType().Namespace;
                Type typeA = Type.GetType(new Program().GetType().Namespace + "." + "PrinterA", true, true);
                Type typeB = Type.GetType(new Program().GetType().Namespace + "." + "PrinterB", true, true);
                lstType.Add(typeA);
                lstType.Add(typeB);
                foreach (Type type in lstType)
                {
                    var temp = Activator.CreateInstance(type);
                    MethodInfo method = type.GetMethod("Print");
                    object[] obj = new object[1];
                    obj[0] = type.Name;
                    method.Invoke(temp, obj);
                }
            }
        }
    }
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleReflect
    {
        class PrinterA
        {
            public void Print(object obj)
            {
                if (obj != null)
                {
                    Console.WriteLine(obj.ToString());
                }
                else
                {
                    Console.WriteLine("PrinterA参数为空!");
                    Console.Read();
                }
            }
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleReflect
    {
        class PrinterB
        {
            public void Print(object obj)
            {
                if (obj != null)
                {
                    Console.WriteLine(obj.ToString());
                    Console.Read();
                }
                else
                {
                    Console.WriteLine("PrinterB参数为空!");
                    Console.Read();
                }
            }
        }
    }
  • 相关阅读:
    文档根元素 "beans" 必须匹配 DOCTYPE 根 "null"
    web.xml配置参数context-param和init-param的区别
    web.xml中通过contextConfigLocation的读取spring的配置文件
    Web.xml配置详解之context-param
    xml 文件 和xsd 文件的关系
    事务并发控制
    Java泛型详解
    MongoDB集群
    MongoDB集群——分片
    MongoDB集群——副本集
  • 原文地址:https://www.cnblogs.com/sumuncle/p/4346873.html
Copyright © 2011-2022 走看看