C#检查字符串是否等于常量名称

时间:2019-05-23 12:39:00

标签: c#

我不确定这是否完全可能,或者我是否应该使用const之后的其他内容。

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

我想要什么:

{
  "0": true,
  "1": {
    "health": 99,
    "position": {
      "x": 1245, /** position and health changed, send them **/
      "y": 1866 /** even if only the x changed, send y too **/
    }
  },
  "2": true /** all the entity stayed the same, so send `true` **/
}

给出字符串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"的值。

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

AllPlace1

1 个答案:

答案 0 :(得分:8)

您可以改用字典:

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);
}