Overriding constants in derived classes in 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# 派生类中的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:覆盖 C# 派生类中的常量
基础教程推荐
- Moq It.Is<>不匹配 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
