使用反射,如何使用最少的代码获得使用C#3.0/.NET 3.5实现接口的所有类型,并最大限度地减少迭代?
这就是我想要重写的内容:
foreach (Type t in this.GetType().Assembly.GetTypes())
if (t is IMyInterface)
; //do stuff
Run Code Online (Sandbox Code Playgroud) 我想调用具有某个属性的方法.所以我循环遍历所有程序集和所有方法以使用我的属性查找方法.工作正常,但是当我得到它的MethodInfo时,如何调用某个方法.
AppDomain app = AppDomain.CurrentDomain;
Assembly[] ass = app.GetAssemblies();
Type[] types;
foreach (Assembly a in ass)
{
types = a.GetTypes();
foreach (Type t in types)
{
MethodInfo[] methods = t.GetMethods();
foreach (MethodInfo method in methods)
{
// Invoke a certain method
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我不知道包含该特定方法的类的实例.所以我无法正确调用它,因为这些方法不是静态的.我还想避免在可能的情况下创建此类的新实例.