Skip to main content
 首页 » 编程设计

c#之如何在派生类时更改常量或静态变量的值

2024年02月06日14duanxz

我有一个与此类似的问题:Can I have a base class where each derived class has its own copy of a static property? ,但那里的答案对我来说似乎不是很确定。

基本上,我有一个具有常量属性的类,我想派生一个具有所有相同方法但对变量使用不同值的类。举一个简单的类比,假设我有一个类,部分看起来像这样:

public class Triangle 
{ 
    public const NumSides = 3; 
    int sideLength; 
 
    public int Perimeter() 
    { 
        return NumSides * sideLength; 
    } 
} 

现在我想创建一个与 Triangle 类完全一样的 Square 类,除了 NumSides 现在是 4。

换句话说,我想要一个现在看起来像这样的类:

public class Square : Triangle 
{ 
    public const NumSides = 4; 
} 

但它仍然可以访问 Triangle 类的所有方法。 (如有必要,我可以编写一个新的构造函数,但我不想从原始类中复制十几个方法。它们的行为应该完全相同,但 NumSides 现在有一个值4.)

我不知道如何做到这一点,要么将 NumSides 设置为常量,要么将其设置为仅具有 get 函数的静态属性。如果我尝试覆盖常量,我会得到“修饰符‘覆盖’对此项无效。”当我尝试覆盖静态属性版本时,我收到等效于“静态成员 Triangle.NumSides 不能标记为覆盖、虚拟或抽象”的消息。

而且,是的,我已经尝试创建一个 Shape 类,将所有功能放入其中,然后让 Triangle 和 Square 都继承自该类。不过,我遇到了与 NumSides 相同的问题。如何在派生新类时更改常量或静态变量/属性的有效值?

请您参考如下方法:

And, yes, I've tried creating a Shape class, putting all the functionality in there, and then having both Triangle and Square inherit from that class.

这是正确的做法。 Square 不是 Triangle,不应将其子类化。

I run into the same problem with NumSides though. How can I change the effective value of a constant or static variable/property when deriving a new class?

您不能使用静态变量。您需要使用非静态变量,但如果您愿意,它们可以是由局部常量支持的属性。话虽这么说,考虑到这里的简单性,我会这样做:

public abstract class Shape 
{ 
   public abstract int NumSides { get; } 
   // Other functionality... 
} 

覆盖方式:

public override int NumSides { get { return 3; } } // For triangle