将const存储在结构体或静态类中

本文关键字:静态类 结构体 const 存储 | 更新日期: 2023-09-27 18:19:04

如果我有一组字符串常量,我想存储类似于enum,是最好使用structstatic 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";
}

将const存储在结构体或静态类中

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

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