c# - 覆盖重叠方法

标签 c# .net cil

问题很短,但我没有找到解决方案。

假设我们有类层次结构

public abstract class A
{
    public virtual string Print() { return "A"; }
}

public class B : A
{
    public virtual new string Print() { return "B"; }
}

public class C : B
{
    public override string Print() { return "C"; }
} 

是否可以在 C 类中重写 A.Print?我尝试将其作为显式接口(interface)实现来实现:

string A.Print() { return "C"; }

但是这里我得到一个错误:

'A' in explicit interface declaration is not an interface

我认为这根本不可能,但希望能收到任何额外信息

最佳答案

在 C# 中不能,但在 IL 中可以通过使用 .override 关键字来覆盖方法将使用的 vtable 槽。 (注意:方法名 Namespace.A.Print 并不重要,在方法名中包含完整的类型名只是避免冲突的一种有用方式,就像 C# 对显式接口(interface)所做的一样实现)

.class public auto ansi beforefieldinit Namespace.C
    extends [x]Namespace.B
{
    .method private hidebysig virtual 
        instance string Namespace.A.Print () cil managed 
    {
        .override method instance string [x]Namespace.A::Print()
        .maxstack 1
        ldstr "C"
        ret
    }
}

关于c# - 覆盖重叠方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29891213/

相关文章:

c# - 使用 Linq 选择 top1

c# - 是否可以等待空文字?

c# - 无法保存自定义集合用户设置

.net - 编码(marshal)委托(delegate)给 std::function

.net - On Error Resume Next 的 CIL 实现

c# - 保存方法和结果

c# - 将索引添加到 DataGridView header

c# - 有没有工具可以在 Visual Studio 中选择一些代码并让它显示相应的 MSIL?

.net - CIL 委托(delegate)行为与目标方法的冲突 "staticness"

c# - Expression<TDelegate>.Compile 在中等信任环境中