.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();
            }
        }
    }
}
原文地址:https://www.cnblogs.com/sumuncle/p/4346873.html