如何确定MethodInfo是否是基本方法的覆盖
我试图确定我从类型实例上的GetMethod调用获得的MethodInfo对象是由类型还是由它的基类实现的。
例如:
Foo foo = new Foo(); MethodInfo methodInfo = foo.GetType().GetMethod("ToString",BindingFlags|Instance);
ToString方法可以在Foo类中实现。 我想知道我是否得到了foo实现?
相关问题
是否可以判断派生类中是否已覆盖.NET虚方法?
检查其DeclaringType
属性。
if (methodInfo.DeclaringType == typeof(Foo)) { // ... }
而不是使用reflection更快的方式是使用委托! 特别是在新版本的框架中,操作非常快。
public delegate string ToStringDelegate(); public static bool OverridesToString(object instance) { if (instance != null) { ToStringDelegate func = instance.ToString; return (func.Method.DeclaringType == instance.GetType()); } return false; }
您将要查看DeclaringType属性。 如果ToString方法来自Foo,则DeclaringType将为Foo类型。
您必须检查MemberInfo
对象的MemberInfo
属性( DeclaringType
实际获取声明此成员的类 ) 是否等于 ReflectedType
属性( 它获取用于获取MemberInfo
此实例的类对象 )。
除此之外,您还必须检查属性IsAbstract
。 如果是, 那么绝对不会覆盖被检查的方法,因为“正在抽象”意味着该成员是一个新的声明,它不能在当前类中具有它的实现( 主体 )(而只是在派生类中)。
以下是使用下面提供的扩展方法的示例:
Student student = new Student { FirstName = "Petter", LastName = "Parker" }; bool isOverridden = student.GetType() .GetMethod( name: nameof(ToString), bindingAttr: BindingFlags.Instance | BindingFlags.Public, binder: null, types: Type.EmptyTypes, modifiers: null ).IsOverridden(); // ExtMethod if (isOverridden) { Console.Out.WriteLine(student); }
扩展方法:
using System.Reflection; public static class MethodInfoHelper { /// /// Detects whether the given method is overridden. /// /// The method to inspect. /// if method is overridden, otherwise public static bool IsOverridden(this MethodInfo methodInfo) { return methodInfo.DeclaringType == methodInfo.ReflectedType && !methodInfo.IsAbstract; } }