因此,我试图找出如何获取引用的程序集基类类型。例如,我有以下内容:
解决方案A {
..项目A
.... class w
...... GetAllClassesSubclassOfClassX(){如果匹配则返回构造函数}
-项目B
----抽象类x
------抽象方法A()
..项目C
.... class y:x
......重写methodA()
-项目D
---- class z:x
------重写methodA()
所以我当前的代码拉回了引用,但是我不确定如何查看它们是否是特定类类型的子类。
public List<AbstractCWThirdPartyConsumer> GetAllProviders()
{
AssemblyName[] types = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
List<AbstractCWThirdPartyConsumer> listOfAllProcessors = new List<AbstractCWThirdPartyConsumer>();
foreach (AssemblyName type in types)
{
if (IsSameOrSubclass(listOfAllProcessors.GetType(), type.GetType()))
{
//AbstractCWThirdPartyConsumer proc = (AbstractCWThirdPartyConsumer)type.GetConstructor(Type.EmptyTypes).Invoke(null);
//listOfAllProcessors.Add(proc);
}
}
return listOfAllProcessors;
}
public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
return potentialDescendant.IsSubclassOf(potentialBase);
}
}
任何纠正我的问题的帮助将是有帮助的!提前致谢。
你为什么不使用Type.IsSubclassOf。
像这样重写您的方法。
public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
return potentialDescendant.IsSubclassOf(potentialBase);
}
我也确实相信您的方法来枚举程序集中的所有类型是不正确的,所以这里是一个重写的版本,应该符合您的意图:
using System.Linq;
...
public List<AbstractCWThirdPartyConsumer> GetAllProviders()
{
IEnumerable<Assembly> referencedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Select(Assembly.Load);
List<AbstractCWThirdPartyConsumer> listOfAllProcessors = new List<AbstractCWThirdPartyConsumer>();
foreach (Assembly assembly in referencedAssemblies)
{
foreach(Type type in assembly.ExportedTypes)
{
if (IsSameOrSubclass(typeof(AbstractCWThirdPartyConsumer), type))
{
//AbstractCWThirdPartyConsumer proc = (AbstractCWThirdPartyConsumer)Activator.CreateInstance(type);
//listOfAllProcessors.Add(proc);
}
}
}
return listOfAllProcessors;
}
public bool IsSameOrSubclass(Type potentialBase, Type potentialDescendant)
{
return potentialDescendant.IsSubclassOf(potentialBase);
}
或者,如果您真的想将其压缩到单个Linq-Method-Chain中,请执行以下操作:
public List<AbstractCWThirdPartyConsumer> GetAllProviders()
{
return Assembly.GetExecutingAssembly()
.GetReferencedAssemblies()
.Select(Assembly.Load)
.SelectMany(asm => asm.ExportedTypes)
.Where(exportedType => exportedType.IsSubclassOf(typeof(AbstractCWThirdPartyConsumer)))
.Select(exportedType => (AbstractCWThirdPartyConsumer) Activator.CreateInstance(exportedType))
.ToList();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句