gpt4 book ai didi

c# - 是否可以区分重写和隐藏方法?

转载 作者:太空狗 更新时间:2023-10-29 18:29:04 25 4
gpt4 key购买 nike

考虑这些变体:

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;
}
}

最佳答案

更新:文档似乎暗示 IsHideBySig 是答案,但在实践中似乎并非如此。

另一种策略是依赖 NewSlot 的存在属性:

public static bool HasNewModifier(this MethodInfo method)
{
return (method.Attributes & MethodAttributes.VtableLayoutMask)
== MethodAttributes.NewSlot;
}

Original, incorrect answer follows.

您可以信赖 IsHideBySig属性(property)。如果方法有 new 修饰符,它将是 true

请注意,以上仅适用于 C# 方法。该文档详细说明了:

When a member in a derived class is declared with the C# new modifier or the Visual Basic Shadows modifier, it can hide a member of the same name in the base class. C# hides base class members by signature. That is, if the base class member has multiple overloads, the only one that is hidden is the one that has the identical signature. By contrast, Visual Basic hides all the base class overloads. Thus, IsHideBySig returns false on a member declared with the Visual Basic Shadows modifier, and true on a member declared with the C# new modifier.

关于c# - 是否可以区分重写和隐藏方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23825134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com