使用Reflection来查找实现指定接口的类及将其实例化的方法
使用仿射添加实现了IEncryptAlgorithm接口的类,并实例化,添加到列表中。
Assembly assembly = Assembly.GetExecutingAssembly(); //获取当前执行程序集
Type[] types = assembly.GetTypes(); //获取程序集中的类
foreach (Type type in types)
{
Type typeInterface = type.GetInterface("IEncryptAlgorithm"); //如果未实现接口,返回值为null
if (typeInterface != null && type.IsInterface == false)
{
//创建实现该接口的对象
IEncryptAlgorithm encryptAlgo = assembly.CreateInstance(type.FullName) as IEncryptAlgorithm;
mArrayAlgorithm.Add(encryptAlgo);
}
}