覆盖 C# 派生类中的常量

Overriding constants in derived classes in C#(覆盖 C# 派生类中的常量)
本文介绍了覆盖 C# 派生类中的常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 中,可以在派生类中重写常量吗?我有一组相同的类,除了一些常量值,所以我想创建一个定义所有方法的基类,然后在派生类中设置相关常量.这可能吗?

In C# can a constant be overridden in a derived class? I have a group of classes that are all the same bar some constant values, so I'd like to create a base class that defines all the methods and then just set the relevant constants in the derived classes. Is this possible?

我宁愿不只是将这些值传递给每个对象的构造函数,因为我希望增加多个类的类型安全性(因为两个具有不同常量的对象进行交互是没有意义的).

I'd rather not just pass in these values to each object's constructor as I would like the added type-safety of multiple classes (since it never makes sense for two objects with different constants to interact).

推荐答案

如果你想覆盖它,它不是一个常量;).尝试虚拟只读属性(或受保护的 setter).

It's not a constant if you want to override it ;). Try a virtual read-only property (or protected setter).

只读属性:

public class MyClass {
    public virtual string MyConst { get { return "SOMETHING"; } }
}
...
public class MyDerived : MyClass {
    public override string MyConst { get { return "SOMETHINGELSE"; } }
}

受保护的设置器:

public class MyClass {
    public string MyConst { get; protected set; }

    public MyClass() {
        MyConst = "SOMETHING";
    }
}

public class MyDerived : MyClass {
    public MyDerived() {
        MyConst = "SOMETHING ELSE";
    }
}

这篇关于覆盖 C# 派生类中的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)