C# 如何确定MethodInfo是否是基方法的重写
我试图确定从对类型实例的GetMethod调用中获得的MethodInfo对象是由类型实现的还是由它的基实现的 例如:C# 如何确定MethodInfo是否是基方法的重写,c#,.net,reflection,overriding,methodinfo,C#,.net,Reflection,Overriding,Methodinfo,我试图确定从对类型实例的GetMethod调用中获得的MethodInfo对象是由类型实现的还是由它的基实现的 例如: Foo foo = new Foo(); MethodInfo methodInfo = foo.GetType().GetMethod("ToString",BindingFlags|Instance); ToString方法可以在Foo类中实现,也可以不在Foo类中实现。我想知道我是否得到了foo实现 相关问题 检查其DeclaringType属性 if (method
Foo foo = new Foo();
MethodInfo methodInfo = foo.GetType().GetMethod("ToString",BindingFlags|Instance);
ToString方法可以在Foo类中实现,也可以不在Foo类中实现。我想知道我是否得到了foo实现
相关问题
检查其
DeclaringType
属性
if (methodInfo.DeclaringType == typeof(Foo)) {
// ...
}
您需要查看DeclaringType属性。如果ToString方法来自Foo,那么DeclaringType将是Foo类型。使用代理比使用反射更快! 特别是在新版本的框架中,操作速度非常快
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;
}
您必须检查
MemberInfo
对象的DeclaringType
属性(DeclaringType
实际获取声明此成员的类)是否等于ReflectedType
属性(获取用于获取MemberInfo
实例的类对象)
除此之外,您还必须检查属性IsaStract如果它是true
,那么检查的方法肯定不会被覆盖,因为“抽象”意味着这个成员是一个新的声明,不能在当前类中(而只能在派生类中)拥有它的实现(主体)
下面是使用下面提供的扩展方法的示例:
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
{
/// <summary>
/// Detects whether the given method is overridden.
/// </summary>
/// <param name="methodInfo">The method to inspect.</param>
/// <returns><see langword="true" /> if method is overridden, otherwise <see langword="false" /></returns>
public static bool IsOverridden(this MethodInfo methodInfo)
{
return methodInfo.DeclaringType == methodInfo.ReflectedType
&& !methodInfo.IsAbstract;
}
}
使用系统反射;
公共静态类MethodInfoHelper
{
///
///检测给定的方法是否被重写。
///
///检查的方法。
///如果方法被重写,则为
公共静态布尔值已溢出(此MethodInfo MethodInfo)
{
return methodInfo.DeclaringType==methodInfo.ReflectedType
&&!methodInfo.IsAbstract;
}
}
如果检查的方法也是抽象方法,则此操作无效。下面是一个例子。实际上,一个方法可以重新抽象,即是抽象重写
。()也许你说的是另一回事——OP问的是如何检测方法是重写,而不是如何检测方法被重写。