views:

144

answers:

2

I am trying to use reflection to determine which methods a derived class overrides from a base class. It is fairly easy to determine if the method is not overridden, but trying to determine if a method is overridden in a base class, or simply created as virtual in the derived class is what I am trying to accomplish.

So, if Class A has virtual methods Process and Export, and Class B has virtual methods Process(overridden), and Display (new virtual method), I would like the following results when examining Class B;

  • Methods Overridden: Process
  • Methods Not Overridden: Export

I only want to deal with the Display method when examining a class that derives from Class B.

+3  A: 

Is GetBaseDefinition what you're after?

Basically

if (method.GetBaseDefinition() == method)
{
    // Method was declared in this class
}

Here's an example showing the cases you're interested in:

using System;
using System.Reflection;

class Base
{
    public virtual void Overridden() {}
    public virtual void NotOverridden() {}
}

class Derived : Base
{
    public override void Overridden() {}
    public virtual void NewlyDeclared() {}
}

public class Test
{
    static void Main()
    {
        foreach (MethodInfo method in typeof(Derived).GetMethods())
        {
            Console.WriteLine("{0}: {1} {2} {3}",
                              method.Name,
                              method == method.GetBaseDefinition(),
                              method.DeclaringType,
                              method.GetBaseDefinition().DeclaringType);
        }
    }
}

Output:

Overridden: False Derived Base
NewlyDeclared: True Derived Derived
NotOverridden: False Base Base
ToString: False System.Object System.Object
Equals: False System.Object System.Object
GetHashCode: False System.Object System.Object
GetType: True System.Object System.Object
Jon Skeet
Perfect, exactly what I was looking for. I can't believe I missed it ;).
Rick Mogstad
A: 

I would expect that BindingFlags.DeclaredOnly used with Type.GetMethods() will get you the effect you are looking for:

http://msdn.microsoft.com/en-us/library/4d848zkb(loband).aspx

Ants
This will get me methods that are defined in this class, but once I have a given MethodInfo, I would like to see if it's base definition is in my class.
Rick Mogstad