考虑以下几个变体:
class A
{
public virtual void Doit()
{
}
}
class B : A
{
public new virtual void Doit()
{
}
}
或者
class B : A
{
public override virtual void Doit()
{
}
}
我无法找到调用typeof(B).GetMethod("Doit");
返回结果的差异。
在这两种情况下,MethodInfo.DecalringType
都是类B,并且其他属性似乎相同。我是不是漏掉了什么,还是没有办法区分它们?
更新:
当我在LINQPad中运行示例时,我注意到Attributes
属性略有不同:
对于new virtual
值为- PrivateScope, Public, Virtual, HideBySig, VtableLayoutMask
对于override
- PrivateScope, Public, Virtual, HideBySig
更新2:
我在谷歌上搜索关于VtableLayoutMask
的内容,回到了StackOverflow
更新3:
生成的代码:
public static class MethodInfoExtensions
{
public static bool IsOverriden(this MethodInfo method)
{
Contract.Requires<ArgumentNullException>(method != null, "method");
return method.IsVirtual
&& !method.IsStatic
// overriden exactly in this class
&& method.ReflectedType == method.DeclaringType
// not new and not declared for the first time in the class
&& method.GetBaseDefinition() != method;
}
}