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();
                }
            }
        }
    }
  • 相关阅读:
    Mac安装LightGBM
    用于视频超分辨率的可变形三维卷积
    ORB-SLAM3 单目地图初始化(终结篇)
    重用地图的单目视觉惯导SLAM系统
    2020,我的秋招感悟!
    超详细解读ORB-SLAM3单目初始化(下篇)
    基于改进的点对特征的6D位姿估计
    深入研究自监督单目深度估计:Monodepth2
    ORB-SLAM3 细读单目初始化过程(上)
    基于视觉和惯性传感器的移动机器人手遥操作系统
  • 原文地址:https://www.cnblogs.com/sumuncle/p/4346873.html
Copyright © 2011-2022 走看看