在.Net中是否有办法获取int的单词的字符串值?

tra*_*vis 7 .net vb.net string int integer

例如:

(1).SomeFunction().Equals("one")
(2).SomeFunction().Equals("two")
Run Code Online (Sandbox Code Playgroud)

在我正在使用的情况下,我真的只需要数字1-9,我应该只使用一个开关/选择案例吗?

更新我也不需要本地化.

更新2这是我最终使用的内容:

Private Enum EnglishDigit As Integer
    zero
    one
    two
    three
    four
    five
    six
    seven
    eight
    nine
End Enum

(CType(someIntThatIsLessThanTen, EnglishDigit)).ToString()
Run Code Online (Sandbox Code Playgroud)

Ric*_*ett 11

枚举怎么样?

enum Number
{
    One = 1, // default value for first enum element is 0, so we set = 1 here
    Two,
    Three,
    Four,
    Five,
    Six,
    Seven,
    Eight,
    Nine,
}
Run Code Online (Sandbox Code Playgroud)

然后你可以输入像...这样的东西

((Number)1).ToString()
Run Code Online (Sandbox Code Playgroud)

如果您需要本地化,则可DescriptionAttribute以为每个枚举值添加一个.属性的Description属性将存储资源项的密钥的名称.

enum Number
{
    [Description("NumberName_1")]
    One = 1, // default value for first enum element is 0, so we set = 1 here 

    [Description("NumberName_2")]
    Two,

    // and so on...
}
Run Code Online (Sandbox Code Playgroud)

以下函数将从Description属性中获取属性的值

public static string GetDescription(object value)
{
    DescriptionAttribute[] attributes = null;
    System.Reflection.FieldInfo fi = value.GetType().GetField(value.ToString());
    if (fi != null)
    {
        attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
    }

    string description = null;
    if ((attributes != null) && (attributes.Length > 0))
    {
        description = attributes[0].Description;
    }

    return description;
}
Run Code Online (Sandbox Code Playgroud)

这可以通过以下方式调用:

GetDescription(((Number)1))
Run Code Online (Sandbox Code Playgroud)

然后,您可以从资源文件中提取相关值,或者只返回调用.ToString()if null.

编辑

各种评论者指出(我必须同意)只使用枚举值名称来引用本地化字符串会更简单.

  • 枚举是一个简单的解决方案,除非您需要本地化:) (3认同)
  • 正如我在答案中建议的那样,我宁愿使用枚举名称和枚举值名称作为资源字符串的键.看起来比阅读代码时必须理解的另一个属性更容易.但是,我想,它可以按你的建议工作.顺便说一下,即使travis不需要,我建议在你的枚举中添加`Zero`,因为`0`是任何枚举的有效值,即使没有明确定义:) (2认同)