3 回答
TA贡献1744条经验 获得超4个赞
如果您需要实现特定接口的所有类型的实例(样本),则可以遍历所有类型,检查接口并在找到匹配项的情况下创建实例。
这是一些伪代码,看起来非常像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运行时存储的(可以由调试器/分析器通过检查堆来计算) / stack这样)。
根据您认为需要这样做的原因,可能有更好的解决方法。
- 3 回答
- 0 关注
- 763 浏览
添加回答
举报
