3

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.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
user852436
  • 31
  • 1
  • 3

2 Answers2

5
typeof(MyClass)
    .GetMethods(BindingFlags.Public | BindingFlags.Instance)
    .Where(m => m.IsVirtual);
abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • Ok, so now I need a way to substitute that method for a delegate. Meaning that when someone calls it, I want to execute my delegate instead, passing all the arguments from the method call into my delegate. – user852436 Jul 20 '11 at 14:39
  • @user: Post a new question to ask that. Also see [`DynamicObject.TryGetMember()`](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.trygetmember.aspx) – abatishchev Jul 20 '11 at 14:41
2

MethodBase has an IsVirtual Property.

MethodBase m = typeof(MyClass).GetMethod("MyMethod");
if (m.IsVirtual)
  // yada-yada-yada...
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • Ok, so now I need a way to substitute that method for a delegate. Meaning that when someone calls it, I want to execute my delegate instead, passing all the arguments from the method call into my delegate. – user852436 Jul 20 '11 at 14:39