如何在c#中创建一个常量的静态字符串数组?

时间:2009-07-04 15:51:22

标签: c# constants

我想在我的DLL中提供常量列表。

使用示例:

MyDLL.AddHouse( HouseName, MyDll.HOUSETYPES.Big)
MyDLL.AddHouse( HouseName, MyDll.HOUSETYPES.Small)

尝试:

public static readonly string[] HOUSETYPES =
{
  "Big", "Small"
};

但这只会让我:

MyDLL.AddHouse( HouseName, MyDll.HOUSETYPES.ToString())

有什么想法吗?感谢。

2 个答案:

答案 0 :(得分:5)

尝试使用枚举。在C#中,这是最好的选择。

由于枚举是强类型的,而不是使用带有字符串的API,因此api将采用枚举类型的值。

public enum HouseTypes
{
   Big,
   Small
}
MyDll.Function(HouseTypes Option)
{
}

然后,您可以通过枚举

调用此代码
{
   MyDll.Function(HouseTypes.Big)
}

作为编码风格的FYI,C#中的所有大写仅保留给常量。

答案 1 :(得分:4)

public static class HouseTypes
{
    public const string Big = "Big";
    public const string Small = "Small";
}

遵循.NET命名标准来命名类和变量是个好主意。例如。 class将被称为HouseTypes(Pascal Case)而不是HOUSETYPES(大写)。

相关问题