c# - 将常量存储在结构或静态类中

标签 c# constants

如果我有一组字符串常量想要存储,类似于 enum,最好使用 struct 还是 static class?例如:

public struct Roman
{
    public const string One = "I";
    public const string Five = "V";
    public const string Ten = "X";
}

public static class Roman
{
    public const string One = "I";
    public const string Five = "V";
    public const string Ten = "X";
}

最佳答案

静态类在 C# 环境中更为传统。使用结构的主要缺点是您可能会不小心创建它的实例。静态类将防止这种情况。 (在底层,静态类是abstract sealed,因此您不能创建它的实例,也不能从它派生。您不能创建抽象结构,也不能创建无参数构造函数私有(private)的,因此无法创建“不可构造的”结构。)

这两种方法都不会对常量值的性能或行为产生任何影响。

关于c# - 将常量存储在结构或静态类中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25417839/

相关文章:

c# - EntityFramework Core 自动生成键 id 属性

c# - 如何在 Controller 以外的地方调用 SignalR Clients.All.InvokeAsync()?

c++ - 抛弃方法的常量性

c++ - shared_ptr<T> 到 shared_ptr<T const> 和 vector<T> 到 vector<T const>

java - 错误 : "attribute value must be constant". 我可以在编译时从枚举构造常量吗?

c# - Linq to Entities - Skip 和 Take 的内部行为

C#:如果一个类有两个构造函数,那么这些构造函数共享一些代码的最佳方式是什么?

c - 确保施工安全

c++ - extern const inside namespace 和 static const 类成员之间的区别?

c# - 动态创建VS Project