【发布时间】:2012-09-13 18:26:15
【问题描述】:
情况如下:
我想创建一个测试应用程序,它能够检索 dll 中的所有类和方法,并允许我在运行时调用它们。
我所拥有的是这样的:
假设我有这些课程:
public static class FirstManagerSingleton
{
public static SecondManager Instance
{
return mInstance; // which is a SecondManager private static object
}
}
public class SecondManager
{
public Service1 service1 {get; private set;}
public Service2 service2 {get; private set;}
...
}
public class Service1
{
public bool Method1()
{
return true;
}
public int Method2()
{
return 1;
}
...
}
public class Service2
{
public bool Method1()
{
return false;
}
public int Method2(int aNumber)
{
return aNumber - 1;
}
...
}
我希望能够选择每个“服务”类,调用任何方法并显示其结果。
是否可以使用反射来做到这一点?如果它不是多层的(2 个经理类),我不会那么挣扎。事实是我需要通过如下所示的调用访问服务类:
FirstManagerSingleton.Instance.Service1.Method1;
到目前为止,我已经能够加载程序集并检索几乎所有方法并打印它们。
Assembly assembly = Assembly.LoadFrom("assemblyName");
// through each type in the assembly
foreach (Type type in assembly.GetTypes())
{
// Pick up a class
if (type.IsClass == true)
{
MethodInfo[] methodInfo;
Console.WriteLine("Found Class : {0}", type.FullName);
Type inter = type.GetInterface("I" + type.Name, true);
if (inter != null)
{
methodInfo = inter.GetMethods();
foreach (MethodInfo aMethod in test2)
{
Console.WriteLine("\t\tMethods : " + aMethod);
}
}
}
}
从那里开始,我真的不知道接下来要做什么来调用这些方法。 顺便说一下,这些方法可以接受一些参数并有一些返回类型。
我正在使用接口来检索方法,以便从从另一个接口继承的方法中进行过滤。
我希望我已经足够清楚了。抱歉,我不能发布真正的代码示例,但我想这足以说明这个概念。
【问题讨论】:
-
是的,有可能。现在我在黑暗中猛烈抨击你想要更多的答案。如果您有更多问题,这将有所帮助。我会快点,否则这可能会被关闭。
-
是的!不过what have you tried?
-
你如何识别哪个类是服务?按名字?服务类是否保证具有无参数构造函数?他们所有的方法都是无参数的吗?
-
@TonyHopkinson 问题已添加
-
所以您想反思性地查看 Singleton 的所有成员以查看您可以访问的内容,然后反思性地查看返回对象的成员并调用其中的一个/多个?我很困惑您是在询问使用反射来查找程序集中的所有内容还是使用反射来使用特定的单例对象。
标签: c# reflection singleton invoke