我们需要获取实现给定接口(interface)的对象的所有实例 - 我们可以这样做吗?如果可以的话,怎么做?
最佳答案
如果您需要实现特定接口(interface)的所有类型的实例(示例),您可以遍历所有类型,检查接口(interface)并在找到匹配项时创建实例。
这是一些看起来非常像 C# 的伪代码,甚至可以编译并返回您需要的内容。如果不出意外,它将为您指明正确的方向:
public static IEnumerable<T> GetInstancesOfImplementingTypes<T>()
{
AppDomain app = AppDomain.CurrentDomain;
Assembly[] ass = app.GetAssemblies();
Type[] types;
Type targetType = typeof(T);
foreach (Assembly a in ass)
{
types = a.GetTypes();
foreach (Type t in types)
{
if (t.IsInterface) continue;
if (t.IsAbstract) continue;
foreach (Type iface in t.GetInterfaces())
{
if (!iface.Equals(targetType)) continue;
yield return (T) Activator.CreateInstance(t);
break;
}
}
}
}
现在,如果您正在谈论遍历堆并返回实现特定类型的所有对象的先前实例化实例,那么祝您好运,因为此信息不由 .Net 运行时存储(可以由调试器/分析器计算通过检查堆/堆栈)。
根据您认为需要这样做的原因,可能有更好的方法。
关于c# - 如何获取实现给定接口(interface)的所有加载类型的所有实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40615126/