程序结构如下
ns.IUser(接口)
ns.BigUsers(类)
ns.SmallUsers(类)
ns.Users(类)现在想写个方法
public ArrayList<IUser> GetAllUsers(string interfaceName){
ArrayList<IUser> ay =new ArrayList<IUser>();
ay.add(new BigUsers());ay.add(new SmallUsers());ay.add(new Users());
return ay;
}有没有人能写出个动态的。根据接口名能得到实现此接口的所有类的实例的集合呀?谢谢。
ns.IUser(接口)
ns.BigUsers(类)
ns.SmallUsers(类)
ns.Users(类)现在想写个方法
public ArrayList<IUser> GetAllUsers(string interfaceName){
ArrayList<IUser> ay =new ArrayList<IUser>();
ay.add(new BigUsers());ay.add(new SmallUsers());ay.add(new Users());
return ay;
}有没有人能写出个动态的。根据接口名能得到实现此接口的所有类的实例的集合呀?谢谢。
因为命名空间并不是一个逻辑结构,只是类似于一种名字前缀。所以只能通过遍历当前加载的所有DLL的所有类成员来找到命名空间下当前的所有类成员。当有新DLL被加载之后,就可能会有新的成员出现。
{
static void Main(string[] args)
{
var asm = Assembly.Load("4.0Test");
var types = asm.GetTypes();
var instances = new List<IA>();
foreach (var temp in types)
{
var tempInterface = temp.GetInterface("IA");
if (tempInterface != null && tempInterface == typeof(IA))
{
var instance = Activator.CreateInstance(temp);
if (instance is IA)
{
instances.Add(instance as IA);
}
}
}
Console.Read();
}
} public interface IA
{ } public class B : IA
{
} public class C : IA
{
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Reflection;namespace _4._0Test
{
class Program
{
static void Main(string[] args)
{
var temp = GetInstance("IA");
Console.Read();
} public static List<IA> GetInstance(string interfaceName)
{
var asm = Assembly.Load("4.0Test");//改成你的程序集名称或者路劲
var types = asm.GetTypes();
var instances = new List<IA>();
foreach (var temp in types)
{
var tempInterface = temp.GetInterface(interfaceName);
if (tempInterface != null && tempInterface == typeof(IA))
{
var instance = Activator.CreateInstance(temp);
if (instance is IA)
{
instances.Add(instance as IA);
}
}
}
return instances;
}
} public interface IA
{ } public class B : IA
{
} public class C : IA
{
}
}