如何判断MemberInfo是否表示替代 [英] How to tell if MemberInfo represents an override

查看:76
本文介绍了如何判断MemberInfo是否表示替代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码:

public class Base {
    public virtual void Method() { }
}

public class Derived : Base {
    public override void Method() { }
}

...

var baseMethodInfo = typeof(Base).GetMember("Method")[0];
var derivedMethodInfo = typeof(Derived).GetMember("Method")[0];

是否可以确定派生的方法信息是否表示一个方法声明,该方法声明将覆盖基类中的另一个方法?

Is it possible to determine if the derivedMethodInfo represents a method declaration which overrides another in a base class?

另一个问题已观察到,如果在基类derivedMethodInfo.DeclaringType中将Method声明为抽象(而不是未实现),它将变成Base,这在阅读@EricLippert的注释后才有意义.我注意到在本示例中,由于派生类重新声明了该方法,即derivedMethodInfo.DeclaringType == derivedMethodInfo.ReflectedType,即.派生.

In another question it was observed that had Method been declared abstract (and not implemented) in the base class, derivedMethodInfo.DeclaringType would have turned up as Base, which makes sense after reading @EricLippert's comments. I noticed that in the present example, since the derived class re-declares the method, that derivedMethodInfo.DeclaringType == derivedMethodInfo.ReflectedType, viz. Derived.

baseMethodInfo和derivedMethodInfo之间似乎没有任何联系,只是它们的名称相同并且它们各自的声明类型出现在同一继承链中.有没有更好的方法建立连接?

There doesn't seem to be any connection between baseMethodInfo and derivedMethodInfo, other than their names are the same and their respective declaring types appear in the same inheritance chain. Is there any better way to make the connection?

我问的原因是,似乎没有办法通过反思来区分前面的示例和下面的示例:

The reason I ask is that there appears to be no way to distinguish, through reflection, between the earlier example and the following one:

public class Base {
    public virtual void Method() { }
}

public class Derived : Base {
    public new void Method() { }
}

在这种情况下,派生类也声明并反映了一个称为Method的成员.

In this case as well, the Derived class both declares and reflects a member called Method.

推荐答案

还有一个更具体的类MethodInfo,它是从MemberInfo派生的.请注意,并非所有类型的成员都可以是虚拟的(例如,字段不能如此).

There's a more specific class MethodInfo which derives from MemberInfo. Note that not all kinds of members can be virtual (fields cannot, for example).

如果你说

var derivedMethodInfo = typeof(Derived).GetMethod("Method");

然后您可以检查

derivedMethodInfo.GetBaseDefinition() == derivedMethodInfo

还是不.请参阅GetBaseDefinition()文档,其中有一个代码示例.

or not. See documentation for GetBaseDefinition() where they also have a code example.

这篇关于如何判断MemberInfo是否表示替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆