gpt4 book ai didi

c# - 如何覆盖常量派生类?

转载 作者:太空狗 更新时间:2023-10-29 22:03:06 24 4
gpt4 key购买 nike

代码:

public class A {
public const int beingSupportedRate = 0;
}

public partial class B : A {
public const int beingSupportedRate = 1;

}

由于性能原因,我希望它像 const int 一样明确。将 virtual 放在 class A 变量 beingSupportedRate 前面会导致编译器错误如下:

修饰符“virtual”对此项目无效

最佳答案

您应该使用 new 关键字来显式隐藏继承的成员:

public class A
{
public const int beingSupportedRate = 0;
}

public class B : A
{
public new const int beingSupportedRate = 1;
}

请记住,您不能从实例访问常量成员。

Console.WriteLine(A.beingSupportedRate);
Console.WriteLine(B.beingSupportedRate);

输出:

0
1

使用此解决方案时应考虑一些问题。以下面的控制台程序为例:

class Program
{
static void Main(string[] args)
{
A a = new A();
B b = new B();
C c = new C();

a.GetBeingSupportRate();
b.GetBeingSupportRate();
c.GetBeingSupportRate();

Console.Read();
}

public class A
{
public const int beingSupportedRate = 0;
public void GetBeingSupportRate()
{
Console.WriteLine(beingSupportedRate);
}
}

public class B : A
{
public new const int beingSupportedRate = 1;

}

public class C : B
{

}
}

这将为所有三个类实例输出 0,因为继承的方法使用 A 中的常量值。这意味着您将必须覆盖所有引用该常量的方法。

首选方法是使用具有必须实现的属性的接口(interface),而不是为此目的使用常量。

关于c# - 如何覆盖常量派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15158486/

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