gpt4 book ai didi

c# - 覆盖重叠方法

转载 作者:太空狗 更新时间:2023-10-29 23:06:45 26 4
gpt4 key购买 nike

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

假设我们有类层次结构

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/

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