12.3. Finding Overridden Methods
Problem
You have an inheritance hierarchy that is several levels deep and has many virtual and overridden methods. You need to determine which method in a derived class overrides what method in one of many possible base classes.
Solution
Use the
MethodInfo.GetBaseDefinition
method to determine
which method is overridden in what base class. The following
overloaded method, FindMethodOverrides
, examines
all of the static and public instance methods in a class and displays
which methods override their respective base class methods. This
method also determines which base class the overridden method is in.
This overloaded method accepts an assembly path and name along with a
type name in which to find overriding methods. Note that the
typeName
parameter must be the fully
qualified type name (i.e., the complete namespace hierarchy, followed
by any containing classes, followed by the type name you are
querying):
public void FindMethodOverrides(string asmPath, string typeName) { Assembly asm = Assembly.LoadFrom(asmPath); Type asmType = asm.GetType(typeName); Console.WriteLine("---[" + asmType.FullName + "]---"); // get the methods that match this type MethodInfo[] methods = asmType.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly); foreach (MethodInfo method in methods) { Console.WriteLine("Current Method: " + method.ToString( )); // get the base method MethodInfo baseDef ...
Get C# Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.