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);
}
}
}
}
}
}