Use reflection to find all public virtual methods and provide an override

此生再无相见时 提交于 2019-12-22 11:08:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!