assembly.GetTypes()

作者:追风剑情 发布于:2014-6-25 22:59 分类:C#

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

标签: GetTypes

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号