有时候,为了快速批量处理已经实现某个基类或者某个接口的子类,需要通过反射的方式获取到他们的类类型(Type),然后再通过

Activator.CreateInstance(objType);

或者

Assembly.Load(path).CreateInstance(typeName);

或者

Assembly.LoadFile(filePath).CreateInstance(typeName);

创建对象实例。

以下通过一个简单的示例来展示:
1,获取当前程序集中的全部类型;
2,判断某一类型是否是继承与另一类型;
3,根据类型名动态创建对象。

目前还有个疑问,不知道谁能解答:
1,如何判断某个类是否实现了某个接口,目前只能先 new 一个对象,然后再 用 is 判断。

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Diagnostics;

namespace com.hetaoos
{

    class Test
    {
        public Test()
        {
            var types = Assembly.GetExecutingAssembly().GetTypes();
            var baseType = typeof(BaseProcessor);
            List<BaseProcessor> processors = new List<BaseProcessor>();
            foreach (var t in types)
            {
                var tmp = t.BaseType;
                while (tmp != null)
                {
                    if (tmp == baseType)
                    {
                        BaseProcessor obj = MethodMaker.CreateObject(t.FullName) as BaseProcessor;
                        if (obj != null)
                        {
                            processors.Add(obj);
                        }
                        break;
                    }
                    else
                    {
                        tmp = tmp.BaseType;
                    }
                }
            }

            Debug.Print("Processor Count:{0}", processors.Count);
            foreach (var p in processors)
            {
                Debug.Print("{0}\t:{1}", p, p.Calc(2, 5));
            }
        }
    }

    public class MethodMaker
    {

        /// <summary>
        /// 创建对象(当前程序集)
        /// </summary>
        /// <param name="typeName">类型名</param>
        /// <returns>创建的对象,失败返回 null</returns>
        public static object CreateObject(string typeName)
        {
            object obj = null;
            try
            {
                Type objType = Type.GetType(typeName, true);
                obj = Activator.CreateInstance(objType);
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
            }
            return obj;
        }

        /// <summary>
        /// 创建对象(外部程序集)
        /// </summary>
        /// <param name="path"></param>
        /// <param name="typeName">类型名</param>
        /// <returns>创建的对象,失败返回 null</returns>
        public static object CreateObject(string path, string typeName)
        {
            object obj = null;
            try
            {

                obj = Assembly.Load(path).CreateInstance(typeName);
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
            }

            return obj;
        }
    }

    public abstract class BaseProcessor
    {
        public abstract int Calc(int a, int b);
    }

    public class Adder : BaseProcessor
    {
        public override int Calc(int a, int b)
        {
            return a + b;
        }
    }

    public class Multiplier : BaseProcessor
    {
        public override int Calc(int a, int b)
        {
            return a * b;
        }
    }
}

输出结果为:

Processor Count:2
com.hetaoos.Adder	:7
com.hetaoos.Multiplier	:10

PS:
判断某个类是否继承自某个接口、类的方法:

        public static bool IsParent(Type test, Type parent)
        {
            if (test == null || parent == null || test == parent || test.BaseType == null)
            {
                return false;
            }
            if (parent.IsInterface)
            {
                foreach (var t in test.GetInterfaces())
                {
                    if (t == parent)
                    {
                        return true;
                    }
                }
            }
            else
            {
                do
                {
                    if (test.BaseType == parent)
                    {
                        return true;
                    }
                    test = test.BaseType;
                } while (test != null);

            }
            return false;
        }