使用反射来获得DLL一定基础类型的所有类 [英] Using reflection to get all classes of certain base type in dll
问题描述
我有一个包含了许多,所有从CommandBase类继承的类的DLL。我试图让所有使用C#反射这些类(CommandA,CommandB,CommandC等)的情况下,这样我可以调用每一个特定的方法。以下是我迄今为止:
I have a dll that contains a number of classes that all inherit from a CommandBase class. I'm trying to get instances of all of these classes (CommandA, CommandB, CommandC, etc...) using reflection in C# so that I can call a specific method on each one. Here is what I have so far:
//get assemblies in directory.
string folder = Path.Combine(HttpContext.Current.Server.MapPath("~/"), "bin");
var files = Directory.GetFiles(folder, "*.dll");
//load each assembly.
foreach (string file in files)
{
var assembly = Assembly.LoadFile(file);
if (assembly.FullName == "MyCommandProject")
{
foreach (var type in assembly.GetTypes())
{
if (!type.IsClass || type.IsNotPublic) continue;
if(type is CommandBase)
{
var command = Activator.CreateInstance(type) as CommandBase;
}
}
}
}
我M有2个问题。第一问题是该行如果(类型为CommandBase),给出了以下警告:
I'm having 2 issues. The 1st issue is that the line "if(type is CommandBase") gives the following warning:
给定的表达式是从来没有提供的类型CommandBase的<。 / STRONG>
The given expression is never of the provided type CommandBase.
第二问题是,我无法弄清楚如何获得的实际对象(CommandA,CommandB等)的一个实例,只将其转换为CommandBase是不够的。
The 2nd issue is that I can't figure out how to get an instance of the actual object (CommandA, CommandB, etc...), just converting it to CommandBase isn't enough.
推荐答案
这是我使用基于接口的加载了该方法。
This is the method I use to load up based on an interface.
private static List<T> GetInstances<T>()
{
return (from t in Assembly.GetExecutingAssembly().GetTypes()
where t.GetInterfaces().Contains(typeof (T)) && t.GetConstructor(Type.EmptyTypes) != null
select (T) Activator.CreateInstance(t)).ToList();
}
和下面是拉回到基于基类相同的功能。
And here's the same function that pulls back based on base class.
private static IList<T> GetInstances<T>()
{
return (from t in Assembly.GetExecutingAssembly().GetTypes()
where t.BaseType == (typeof(T)) && t.GetConstructor(Type.EmptyTypes) != null
select (T)Activator.CreateInstance(t)).ToList();
}
当然,这将需要在参考你略作修改,以点重新载入。
Of course it would need to be modified slightly to point at the reference you're loading.
这篇关于使用反射来获得DLL一定基础类型的所有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!