天天看點

C#通過反射建立接口實作類的執行個體C#通過反射建立接口實作類的執行個體

C#通過反射建立接口實作類的執行個體

namespace AssemblyTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Assembly test = typeof(ITest).Assembly;
            Type[] types = test.GetTypes(); //擷取程式運作時所有涉及ITest的類(接口)
            foreach (Type type in types)
            {
                //判斷該類至少實作了一個接口,且非抽象
                if (type.GetInterfaces().Length > 0 && !type.IsAbstract)
                {
                    //type.GetInterfaces()[0]擷取到直接實作的接口判斷是否所需要的類型
                    //當實作多個接口時需要根據具體的情況擷取
                    if (type.GetInterfaces()[0] == typeof(ITest))
                    {
                        //Activator建立執行個體并強制類型轉換指派
                        ITest testInstance = (ITest)Activator.CreateInstance(type);
                    }
                }
            }
        }
    }
}