如何使用反射调用被派生类重写的基本方法?
class Base
{
public virtual void Foo() { Console.WriteLine("Base"); }
}
class Derived : Base
{
public override void Foo() { Console.WriteLine("Derived"); }
}
public static void Main()
{
Derived d = new Derived();
typeof(Base).GetMethod("Foo").Invoke(d, null);
Console.ReadLine();
}
Run Code Online (Sandbox Code Playgroud)
此代码始终显示"派生"...
我正在做装配分析项目,遇到了问题。
我想要实现的是一个类实现的所有接口的列表,但没有派生接口(以及派生类实现的接口)。
下面是一个示例来说明(来自 LinqPad,.Dump()是一个打印到结果窗口):
void Main()
{
typeof(A).GetInterfaces().Dump(); //typeof(IT), typeof(IT<Int32>)
typeof(B).GetInterfaces().Dump(); //typeof(IT<Int32>)
typeof(C).GetInterfaces().Dump(); //typeof(IT), typeof(IT<Int32>)
}
class C : A {}
class A : IT {}
class B : IT<int> {}
public interface IT : IT <int> {}
public interface IT<T> {}
Run Code Online (Sandbox Code Playgroud)
我想得到的是
typeof(A).GetInterfaces().Dump(); //typeof(IT)
typeof(B).GetInterfaces().Dump(); //typeof(IT<Int32>)
typeof(C).GetInterfaces().Dump(); //
Run Code Online (Sandbox Code Playgroud)
我发现这篇文章Type.GetInterfaces() 对于声明的接口仅带有答案
Type type = typeof(E);
var interfaces = type.GetInterfaces()
.Where(i => type.GetInterfaceMap(i).TargetMethods.Any(m => m.DeclaringType == type))
.ToList();
Run Code Online (Sandbox Code Playgroud)
但我正在寻找是否有一种替代方法可以迭代方法。
有什么办法可以实现这一点吗?