Dynamically create subclass which overrides virtual final methods - c#

I have class and interface:
public class TestClass : ITestInterface
{
public int GetStatus()
{
return -1;
}
}
public interface ITestInterface
{
int GetStatus();
}
and I would like to dynamically create subclass of TestClass which will look like:
public class TestClass2 : TestClass
{
public new int GetStatus()
{
return base.GetStatus();
}
}
I have some code which can create subclasses and overrides all virtual methods but when method is virtual final (GetStatus) I'm getting:
"Declaration referenced in a method implementation cannot be a final method."
Any ideas how it can be done?
PS: I can post code mentioned if you'd like.
EDIT 1:
'Some code':
public static T GetSubClass<T>() where T : class
{
var builder = DefineType<T>();
DefineOverrideMethods(builder, typeof(T));
var type = CreateType(builder);
return (T)Activator.CreateInstance(type);
}
private static TypeBuilder DefineType<T>() where T : class
{
return _moduleBuilder.DefineType("Proxy_" + typeof (T).Name,
TypeAttributes.Sealed | TypeAttributes.Class | TypeAttributes.Public, typeof (T));
}
private static void DefineOverrideMethods(TypeBuilder builder, Type type)
{
foreach (var virtualMethodInfo in GetVirtualMethods(type))
{
var parameters = GetMethodParametersTypes(virtualMethodInfo);
var newMethodInfo = DefineNewVirtualMethod(builder, virtualMethodInfo, parameters);
var il = newMethodInfo.GetILGenerator();
var local = EmitCreateLocal(il, newMethodInfo);
EmitCallBaseMethod(il, virtualMethodInfo);
EmitSaveReturnToLocal(il, local);
EmitReturnMethod(il, virtualMethodInfo, local);
builder.DefineMethodOverride(newMethodInfo, virtualMethodInfo);
}
}
private static IEnumerable<MethodInfo> GetVirtualMethods(Type type)
{
return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(q => q.IsVirtual);
}
private static Type[] GetMethodParametersTypes(MethodInfo virtualMethodInfo)
{
return virtualMethodInfo.GetParameters().Select(q => q.ParameterType).ToArray();
}
private static MethodBuilder DefineNewVirtualMethod(TypeBuilder builder, MethodInfo virtualMethodInfo, Type[] parameters)
{
return builder.DefineMethod(virtualMethodInfo.Name,
MethodAttributes.Public | MethodAttributes.Virtual,
virtualMethodInfo.ReturnType, parameters);
}
private static void EmitSaveReturnToLocal(ILGenerator il, LocalBuilder local)
{
il.Emit(OpCodes.Stloc_S, local);
il.Emit(OpCodes.Ldloc_S, local);
}
private static LocalBuilder EmitCreateLocal(ILGenerator il, MethodBuilder newMethodInfo)
{
return il.DeclareLocal(newMethodInfo.ReturnType);
}
private static Type CreateType(TypeBuilder builder)
{
builder.DefineDefaultConstructor(MethodAttributes.Public);
var type = builder.CreateType();
return type;
}
private static void EmitReturnMethod(ILGenerator il, MethodInfo methodInfo, LocalBuilder local)
{
il.Emit(OpCodes.Ldloc_S, local);
il.Emit(OpCodes.Ret);
}
private static void EmitCallBaseMethod(ILGenerator il, MethodInfo virtualMethodInfo)
{
ushort index = 0;
while (index < virtualMethodInfo.GetParameters().Length + 1)
il.Emit(OpCodes.Ldarg, index++);
il.Emit(OpCodes.Call, virtualMethodInfo);
}
Exception is throwed at var type = builder.CreateType();
EDIT 2:
#Rahul:
Language is C# and as you can see in method 'GetVirtualMethods' there is property 'IsVirtual'.
Property 'IsFinal' exists there too and returns true for 'GetStatus' method.
EDIT 3:
#Wim.van.Gool:
Yes you are right - I can not override non virtual methods. What I am trying to do here is to hide base implementation of 'GetStatus' with dummy implementation which calls base method.
Why it would be useful? Imagine that method 'GetSubClass' returns you a class that behaves like base but for example have added log methods before and after base implementation calls.
#Michał Komorowski:
Thank you for answer. It works, but only partially. Program do not throws error anymore but in this example:
ITestInterface obj = StaticClass.GetSubClass<TestClass>();
obj.GetStatus();
'GetStatus' method is called directly from base (TestClass) not from dynamically created subclass.
I tried to add: builder.AddInterfaceImplementation(typeof(ITestInterface)); but it did not make any difference.
EDIT 4:
#danish: Thank you for answer. It is now working. NewSlot saves problem.
Actually whole attribute data: MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual.
Thank you guys for helping. Unfortunately I can not mark both answers as a correct ones but both were significant for resolving problem.

Whenever a class implements an interface method, CLR needs that method to be marked as virtual and also final is set to true. However in reality this method is not really virtual. To get actual virtual methods, you need to check IsVirtual for true and IsFinal for false.
In your case, you are actually looking for hiding the intended behaviour. Hence a new method needs to be created and emitted for sub class. From what I understand, NewSlot method attribute will shadow the base class method(can someone confirm? I am not too sure about this one).

The problem is that you are actually trying to override a method that is not virtual. You have 2 options. The first one is to make TestClass.GetStatus method virtual. When you do it you will be able to override it. The second solution is to hide this method. It seems to me that your code will work if you:
Remove the following line builder.DefineMethodOverride(newMethodInfo, virtualMethodInfo);
In DefineNewVirtualMethod method use MethodAttributes.HideBySig instead of MethodAttributes.Virtual.

Related

How to call a method in an abstract class

public abstract class BaseClass
{
protected virtual int getValue() { return 1; }
}
I want to call getValue method.
typeof(BaseClass)
.GetMethod("getValue", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
.Invoke(null, new object[] { });
This code has a error.
Non static method requires a target
However, I cannot create instance of BaseClass because it is abstract class.
So, I am using dummy class which extends BaseClass.
class DummyClass : BaseClass { }
typeof(BaseClass)
.GetMethod("getValue", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
.Invoke(new DummyClass(), new object[] { });
I don't want to create dummy class every time if possible.
Is there a better way?
I agree with the other comments that this should not be production code, but out of fun it can certainly be done:
public static T CreateAbstractInstance<T>() where T : class =>
(T)Activator.CreateInstance(
Thread.GetDomain()
.DefineDynamicAssembly(new AssemblyName("DynamicAssembly"), AssemblyBuilderAccess.Run)
.DefineDynamicModule("DynamicModule")
.DefineType("DynamicType", TypeAttributes.Public | TypeAttributes.Class, typeof(T))
.CreateType());
private static TResult AbstractInvoke<TClass, TResult>(string methodName) where TClass : class
{
var method = typeof(TClass).GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
var elegate = method.CreateDelegate(typeof(Func<BaseClass, TResult>));
return (TResult)elegate.DynamicInvoke(CreateAbstractInstance<TClass>());
}
private static void Main()
{
var result = AbstractInvoke<BaseClass, int>("getValue");
Console.WriteLine(result);
}
There is probably some method to trick the compiler and invoke it without even creating an instance, but I was getting too many Visual Studio crashes to carry on investigating other methods. Expressions seems to lead nowhere as at the end of the day, it still had to generate valid code so no way to trick an expression into an invalid lambda.
If you reuse a singleton instance from CreateAbstractInstance then you shouldn't have overheads after the first object is created (beside reflection usage if you invoke non public methods).
I thought I might add this to the answer as well:
I notice the comment about using it in a unit test; if you are using Moq (and probably most of the decent frameworks), you can do this:
var bc = new Mock<BaseClass>().Object;
// Invoke whatever you want on `bc` with reflection or not.
Although be aware that if the method is virtual it will automatically override it so you won't get by default the base class logic, but it can be solved setting up the mock.
You can try using an open instance delegate. Try this:
var method = typeof(BaseClass).GetMethod("getValue");
var func = (Func<BaseClass, int>) Delegate.CreateDelegate(typeof(Func<BaseClass, int>), method);
int result = func(null);
Note: The above technique works by omitting the hidden this parameter in the member call. This will only work if your method does not need to access the instance. If you attempt to access the instance, you will get a null reference exception.

C# - GetMethod returns null

I have A class:
public abstract class A
{
}
And then I have B class that derives from it:
public sealed class B : A
{
public void SomeMethod()
{
var method = this.GetType().GetMethod("AddText");
}
private void AddText(string text)
{
...
}
}
Why is GetMethod returning null?
var methodInfo = this.GetType().GetMethod("AddText", BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[] { typeof(string) }, null);
Your method has a parameter, you need to use the overload that accepts a type array for the parameter types and the binding flags.
In .net Method signatures are based on their name, their return type, and their parameters.
So if your method has parameters you have to tell Reflection what parameter types it has via a Type[].
By default, Reflection will only search for public methods.
You need to pass BindingFlags.Instance | BindingFlags.NonPublic.

Fastest way for Get Value of a property (Reflection) in C#

I want to know what is fastest way to get value (only for this problem) from an object`s property ?
after some searching I saw a post from #MarkGravell in this site
He wrote this code :
using System;
using System.Reflection;
using System.Reflection.Emit;
public class Foo
{
public Foo(int bar)
{
Bar = bar;
}
private int Bar { get; set; }
}
static class Program {
static void Main()
{
var method = new DynamicMethod("cheat", typeof(int),
new[] { typeof(object) }, typeof(Foo), true);
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, typeof(Foo));
il.Emit(OpCodes.Callvirt, typeof(Foo).GetProperty("Bar",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic
).GetGetMethod(true));
il.Emit(OpCodes.Ret);
var func = (Func<object, int>)method.CreateDelegate(
typeof(Func<object, int>));
var obj = new Foo(123);
Console.WriteLine(func(obj));
}
}
OR
var method = typeof(Foo).GetProperty("Bar",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.GetGetMethod(true);
var func = (Func<Foo, int>)
Delegate.CreateDelegate(typeof(Func<Foo, int>), method);
I changed it to
var pt = propertyInfo.PropertyType; // I dont know what is Type
var method = pt.GetProperty("Bar",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
.GetGetMethod(true);
var func = (Func<Foo, object>) // I dont know what is return type so set object !!!
Delegate.CreateDelegate(typeof(Func<Foo, object>), method); // I want get value as object ?!!!
return func(entity).ToString(); // cast return value to string
but I got an exception
Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
I dont know what is my property type It can be anything How customize code for this purpose ?
If anyone can help me in better way (fastest way) without property Type restriction please introduce it
The Delegate.CreateDelegate will not work in this case, because you have to cast the resulting delegate to some known type, otherwise all you have is DynamicInvoke which is not better than direct invocation of PropertyInfo (see here explanation by Marc Gravell).
The most generic way I've seen which does not involve lambda expressions (like
Sriram Sakthivel suggested) is shown by Jon Skeet here. Building on his approach and the fact we can get the actual property return type from PropertyInfo, we can invent something custom-tailored for properties invocation.
First, we define an interface:
public interface IPropertyCallAdapter<TThis>
{
object InvokeGet(TThis #this);
//add void InvokeSet(TThis #this, object value) if necessary
}
Then, an implementation of the interface:
public class PropertyCallAdapter<TThis, TResult> : IPropertyCallAdapter<TThis>
{
private readonly Func<TThis, TResult> _getterInvocation;
public PropertyCallAdapter(Func<TThis, TResult> getterInvocation)
{
_getterInvocation = getterInvocation;
}
public object InvokeGet(TThis #this)
{
return _getterInvocation.Invoke(#this);
}
}
The InvokeGet method looks mostly like the one Jon Skeet uses.
Now, to the "magic" part. We define a service which will build and cache an instance of the provider. It looks like this:
public class PropertyCallAdapterProvider<TThis>
{
private static readonly Dictionary<string, IPropertyCallAdapter<TThis>> _instances =
new Dictionary<string,IPropertyCallAdapter<TThis>>();
public static IPropertyCallAdapter<TThis> GetInstance(string forPropertyName)
{
IPropertyCallAdapter<TThis> instance;
if (!_instances.TryGetValue(forPropertyName, out instance))
{
var property = typeof(TThis).GetProperty(
forPropertyName,
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
MethodInfo getMethod;
Delegate getterInvocation = null;
if (property != null && (getMethod = property.GetGetMethod(true)) != null)
{
var openGetterType = typeof(Func<,>);
var concreteGetterType = openGetterType
.MakeGenericType(typeof(TThis), property.PropertyType);
getterInvocation =
Delegate.CreateDelegate(concreteGetterType, null, getMethod);
}
else
{
//throw exception or create a default getterInvocation returning null
}
var openAdapterType = typeof(PropertyCallAdapter<,>);
var concreteAdapterType = openAdapterType
.MakeGenericType(typeof(TThis), property.PropertyType);
instance = Activator
.CreateInstance(concreteAdapterType, getterInvocation)
as IPropertyCallAdapter<TThis>;
_instances.Add(forPropertyName, instance);
}
return instance;
}
}
Here, without knowing at compile time the exact TResult type, we create the adapter and cache it for subsequent usage in order to prevent heavy reflection calls in the future.
That's it. You can use it in the following way:
PropertyCallAdapterProvider<Foo>.GetInstance("Bar").InvokeGet(fooInstance)
Also, you can easily extend this for property setters if necessary.
On my machine those are the results for accessing the getter in loop ten million times, using various methods, when the adapter instance is pre-fetched from the provider before entering the loop:
141 milliseconds for direct invocation
244 milliseconds for adapter invocation
1800 milliseconds for reflection invocation
8179 milliseconds for dynamic delegate invocation

c# get method names from underlying type using reflection

I'd like to list all method names from the underlyingtype.
I tried
var methods = this.GetType().UnderlyingSystemType.GetMethods();
but doesn't work.
EDIT
Added example
public class BaseClass
{
public BaseClass()
{
var methods = this.GetType().UnderlyingSystemType.GetMethods();
}
}
public class Class1:BaseClass
{
public void Method1()
{}
public void Method2()
{}
}
I need in the collection Method1 and Method 2.
The code you provided works.
System.Exception test = new Exception();
var methods = test.GetType().UnderlyingSystemType.GetMethods();
foreach (var t in methods)
{
Console.WriteLine(t.Name);
}
returns
get_Message
get_Data
GetBaseException
get_InnerException
get_TargetSite
get_StackTrace
get_HelpLink
set_HelpLink
get_Source
set_Source
ToString
GetObjectData
GetType
Equals
GetHashCode
GetType
EDIT:
Is that what you want?
Class1 class1 = new Class1();
var methodsClass1 = class1.GetType().GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
BaseClass baseClass = new BaseClass();
var methodsBaseClass = baseClass.GetType().GetMethods(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
foreach (var t in methodsClass1.Where(z => methodsBaseClass.FirstOrDefault(y => y.Name == z.Name) == null))
{
Console.WriteLine(t.Name);
}
Try something like
MethodInfo[] methodInfos =
typeof(MyClass).GetMethods(BindingFlags.Public |
BindingFlags.Static);
here is an example on how to use reflection to get the Method names
replace MyObject with your Object / Class
using System.Reflection;
MyObject myObject;//The name of the Object
foreach(MethodInfo method in myObject.GetType().GetMethods())
{
Console.WriteLine(method.ToString());
}
The problem lies in the override of GetType which you are calling in the constructor of the BaseClass.
If you create an instance of the Class1 type, and look at the methods you have, you will see all 6 methods.
If you create an instance of the BaseClass type, you will only see 4 methods - the 4 methods on from the Object type.
By creating an instance of the subclass, you are implicitly calling the constructor in the BaseClass. When it uses GetType(), it uses the overridden virtual method of the Class1 type, which returns the expected response.

Detect if a method was overridden using Reflection (C#)

Say I have a base class TestBase where I define a virtual method TestMe()
class TestBase
{
public virtual bool TestMe() { }
}
Now I inherit this class:
class Test1 : TestBase
{
public override bool TestMe() {}
}
Now, using Reflection, I need to find if the method TestMe has been overriden in child class - is it possible?
What I need it for - I am writing a designer visualizer for type "object" to show the whole hierarchy of inheritance and also show which virtual methods were overridden at which level.
Given the type Test1, you can determine whether it has its own implementation declaration of TestMe:
typeof(Test1).GetMethod("TestMe").DeclaringType == typeof(Test1)
If the declaration came from a base type, this will evaluate false.
Note that since this is testing declaration, not true implementation, this will return true if Test1 is also abstract and TestMe is abstract, since Test1 would have its own declaration. If you want to exclude that case, add && !GetMethod("TestMe").IsAbstract
I was unable to get Ken Beckett's proposed solution to work. Here's what I settled on:
public static bool IsOverride(MethodInfo m) {
return m.GetBaseDefinition().DeclaringType != m.DeclaringType;
}
There are tests in the gist.
As #CiprianBortos pointed out, the accepted answer is not complete and will lead to a nasty bug in your code if you use it as-is.
His comment provides the magic solution GetBaseDefinition(), but there's no need to check the DeclaringType if you want a general-purpose IsOverride check (which I think was the point of this question), just methodInfo.GetBaseDefinition() != methodInfo.
Or, provided as an extension method on MethodInfo, I think this will do the trick:
public static class MethodInfoUtil
{
public static bool IsOverride(this MethodInfo methodInfo)
{
return (methodInfo.GetBaseDefinition() != methodInfo);
}
}
A simple solution which will also work for protected member and properties is as follows:
var isDerived = typeof(Test1 ).GetMember("TestMe",
BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.DeclaredOnly).Length == 0;
This is a repost of my answer here, which in turn had made references to this question.
A method that also works in some non trivial cases:
public bool Overrides(MethodInfo baseMethod, Type type)
{
if(baseMethod==null)
throw new ArgumentNullException("baseMethod");
if(type==null)
throw new ArgumentNullException("type");
if(!type.IsSubclassOf(baseMethod.ReflectedType))
throw new ArgumentException(string.Format("Type must be subtype of {0}",baseMethod.DeclaringType));
while(type!=baseMethod.ReflectedType)
{
var methods=type.GetMethods(BindingFlags.Instance|
BindingFlags.DeclaredOnly|
BindingFlags.Public|
BindingFlags.NonPublic);
if(methods.Any(m=>m.GetBaseDefinition()==baseMethod))
return true;
type=type.BaseType;
}
return false;
}
And a few ugly tests:
public bool OverridesObjectEquals(Type type)
{
var baseMethod=typeof(object).GetMethod("Equals", new Type[]{typeof(object)});
return Overrides(baseMethod,type);
}
void Main()
{
(OverridesObjectEquals(typeof(List<int>))==false).Dump();
(OverridesObjectEquals(typeof(string))==true).Dump();
(OverridesObjectEquals(typeof(Hider))==false).Dump();
(OverridesObjectEquals(typeof(HiderOverrider))==false).Dump();
(OverridesObjectEquals(typeof(Overrider))==true).Dump();
(OverridesObjectEquals(typeof(OverriderHider))==true).Dump();
(OverridesObjectEquals(typeof(OverriderNothing))==true).Dump();
}
class Hider
{
public virtual new bool Equals(object o)
{
throw new NotSupportedException();
}
}
class HiderOverrider:Hider
{
public override bool Equals(object o)
{
throw new NotSupportedException();
}
}
class Overrider
{
public override bool Equals(object o)
{
throw new NotSupportedException();
}
}
class OverriderHider:Overrider
{
public new bool Equals(object o)
{
throw new NotSupportedException();
}
}
class OverriderNothing:Overrider
{
}
According to this answer there could also be a simple way to check if a virtual method was overridden without to know the exact derived or base type using a test for the MethodAttributes.NewSlot attribute:
public static bool HasOverride(this MethodInfo method)
{
return (method.Attributes & MethodAttributes.Virtual) != 0 &&
(method.Attributes & MethodAttributes.NewSlot) == 0;
}
Together with another extension method
private const BindingFlags Flags = BindingFlags.NonPublic |
BindingFlags.Public | BindingFlags.Instance;
public static bool HasOverride(this Type type, string name, params Type[] argTypes)
{
MethodInfo method = type.GetMethod(name, Flags, null, CallingConventions.HasThis,
argTypes, new ParameterModifier[0]);
return method != null && method.HasOverride();
}
you could then simply call
bool hasOverride = GetType().HasOverride(nameof(MyMethod), typeof(Param1Type),
typeof(Param2Type), ...);
to check if MyMethod is overridden in a derived class.
As far as I've tested this, it seemed to work fine (on my machine™).
There is a better, safer and faster way to do it.
This technique makes sense if your class instance is going to have a long life and the IsOverridden check must be performed several times.
To solve this problem we can use a cache and C# delegates, much faster than reflection!
// Author: Salvatore Previti - 2011.
/// <summary>We need a delegate type to our method to make this technique works.</summary>
delegate int MyMethodDelegate(string parameter);
/// <summary>An enum used to mark cache status for IsOverridden.</summary>
enum OverriddenCacheStatus
{
Unknown,
NotOverridden,
Overridden
}
public class MyClassBase
{
/// <summary>Cache for IsMyMethodOverridden.</summary>
private volatile OverriddenCacheStatus pMyMethodOverridden;
public MyClassBase()
{
// Look mom, no overhead in the constructor!
}
/// <summary>
/// Returns true if method MyMethod is overridden; False if not.
/// We have an overhead the first time this function is called, but the
/// overhead is a lot less than using reflection alone. After the first time
/// this function is called, the operation is really fast! Yeah!
/// This technique works better if IsMyMethodOverridden() should
/// be called several times on the same object.
/// </summary>
public bool IsMyMethodOverridden()
{
OverriddenCacheStatus v = this.pMyMethodOverridden;
switch (v)
{
case OverriddenCacheStatus.NotOverridden:
return false; // Value is cached! Faaast!
case OverriddenCacheStatus.Overridden:
return true; // Value is cached! Faaast!
}
// We must rebuild cache.
// We use a delegate: also if this operation allocates a temporary object
// it is a lot faster than using reflection!
// Due to "limitations" in C# compiler, we need the type of the delegate!
MyMethodDelegate md = this.MyMethod;
if (md.Method.DeclaringType == typeof(MyClassBase))
{
this.pMyMethodOverridden = OverriddenCacheStatus.NotOverridden;
return false;
}
this.pMyMethodOverridden = OverriddenCacheStatus.Overridden;
return true;
}
/// <summary>Our overridable method. Can be any kind of visibility.</summary>
protected virtual int MyMethod(string parameter)
{
// Default implementation
return 1980;
}
/// <summary>Demo function that calls our method and print some stuff.</summary>
public void DemoMethod()
{
Console.WriteLine(this.GetType().Name + " result:" + this.MyMethod("x") + " overridden:" + this.IsMyMethodOverridden());
}
}
public class ClassSecond :
MyClassBase
{
}
public class COverridden :
MyClassBase
{
protected override int MyMethod(string parameter)
{
return 2011;
}
}
class Program
{
static void Main(string[] args)
{
MyClassBase a = new MyClassBase();
a.DemoMethod();
a = new ClassSecond();
a.DemoMethod();
a = new COverridden();
a.DemoMethod();
Console.ReadLine();
}
}
When you run this program as a console application, it will print:
MyClassBase result:1980 overridden:False
ClassSecond result:1980 overridden:False
COverridden result:2011 overridden:True
Tested with Visual Studio 2010, C# 4.0.
Should work also on previous versions, but it can be a little slower on C# less than 3.0 due to optimizations to delegates in the new releases, tests about this would be appreciated :)
However it will be still faster than using reflection!
public static bool HasOverridingMethod(this Type type, MethodInfo baseMethod) {
return type.GetOverridingMethod( baseMethod ) != null;
}
public static MethodInfo GetOverridingMethod(this Type type, MethodInfo baseMethod) {
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod;
return type.GetMethods( flags ).FirstOrDefault( i => baseMethod.IsBaseMethodOf( i ) );
}
private static bool IsBaseMethodOf(this MethodInfo baseMethod, MethodInfo method) {
return baseMethod.DeclaringType != method.DeclaringType && baseMethod == method.GetBaseDefinition();
}
Simple 1-liner based on this and this answers:
typeof(T).GetMember(nameof("Method")).OfType<MethodInfo>()
.Where(m => m.GetBaseDefinition().DeclaringType != m.DeclaringType);

Categories