问题
I have a project where I want to be able to iterate across an instance of a class and find all methods that are marked public virtual. Then I want to override the instance of the class so that when the method is called I can call a different set of code. I know how to find all methods that are public in a class using reflection, but I cannot figure out how to override virtual methods.
Basically I am giving a proxy object to use, and when they call the method, I want to call a method on the underlying object. I can do this by manually overriding each and every method, but I would like to use something a bit more dynamic.
回答1:
typeof(MyClass)
.GetMethods(BindingFlags.Public | BindingFlags.Instance)
.Where(m => m.IsVirtual);
回答2:
MethodBase has an IsVirtual Property.
MethodBase m = typeof(MyClass).GetMethod("MyMethod");
if (m.IsVirtual)
// yada-yada-yada...
来源:https://stackoverflow.com/questions/6750730/use-reflection-to-find-all-public-virtual-methods-and-provide-an-override