首页 > 解决方案 > C# 检查字符串是否等于 const name

问题描述

我不确定这是否可能,或者我是否应该使用其他东西然后 const。

我有大约 50 个 const 字符串,它们都有唯一的值。该程序将读取一个字符串,该字符串是 const 名称之一。

我想要的是:

private const string AllPlace1 = "1355,-203,-4,0.002551732,0.705572185,0.708626711,0.003092848,-1,0,0,0";
private const string MoveDown1 = "1355,-203,-24,0.002551735,0.705572183,0.708626713,0.00309285,-1,0,0,0";
private const string Free1 = "1355,-108,-24,0.002551719,0.705572218,0.708626678,0.003092837,-1,0,0,0";

"AllPlace1"给出字符串时,系统应该打印出 const 的值AllPlace1

当然,我可以为所有可能性写这样的东西,但这不是我想要为 50 个可能的值做的事情。

if (args[3] == "AllPlace1")
    WriteLine(AllPlace1);
else if (args[3] == "MoveDown1")
    WriteLine(MoveDown1);
etc

标签: c#

解决方案


您可以改用字典:

static readonly Dictionary<string, string> NameValueMapper = new Dictionary<string, string>{
    { "AllPlace1", "1355,-203,-4,0.002551732,0.705572185,0.708626711,0.003092848,-1,0,0,0"},
    { "MoveDown1", "1355,-203,-24,0.002551735,0.705572183,0.708626713,0.00309285,-1,0,0,0"},
    { "Free1"    , "1355,-108,-24,0.002551719,0.705572218,0.708626678,0.003092837,-1,0,0,0"},
};

...

if (NameValueMapper.TryGetValue(args[3], out string value))
{
    WriteLine(value);
}

推荐阅读