Use reflection to find all public virtual methods

2019-05-14 07:51发布

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.

2条回答
聊天终结者
2楼-- · 2019-05-14 08:24
typeof(MyClass)
    .GetMethods(BindingFlags.Public | BindingFlags.Instance)
    .Where(m => m.IsVirtual);
查看更多
Evening l夕情丶
3楼-- · 2019-05-14 08:47

MethodBase has an IsVirtual Property.

MethodBase m = typeof(MyClass).GetMethod("MyMethod");
if (m.IsVirtual)
  // yada-yada-yada...
查看更多
登录 后发表回答