鸟语天空
assembly.GetTypes()
post by:追风剑情 2014-6-25 22:59

using System;
using System.Reflection;

namespace GetTypesTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly asm = Assembly.GetExecutingAssembly();
            Type[] types = asm.GetTypes();
            foreach (Type type in types)
            {
                Type typeInterface = type.GetInterface("ITest");
                if (null != typeInterface)//判断是否实现了ITest接口
                {
                    Object obj = asm.CreateInstance(type.FullName);//通过反射创建对象
                    type.InvokeMember("Fun", BindingFlags.InvokeMethod, null, obj, null);//调用Fun()方法
                }
            }

            Console.ReadLine();
        }
    }

    public interface ITest
    {
        void Fun();
    }

    public class TestA : ITest
    {
        public void Fun()
        {
            Console.WriteLine("TestA->Fun()");
        }
    }

    public class TestB : ITest
    {
        public void Fun()
        {
            Console.WriteLine("TestB->Fun()");
        }
    }
}
运行效果

GetTypes.png

评论:
发表评论:
昵称

邮件地址 (选填)

个人主页 (选填)

内容