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# 派生类中的常量


- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04