c# - 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
解决方案
您可以改用字典:
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);
}
推荐阅读
- json - 如何在 Scala 中将 Array[Reads[JsObject]] 展平为 Reads[JsObject]
- python - 与 functools.partial 相比,Python Lambda 函数执行的调用次数是其两倍
- python - 状态测试中途放弃,从头开始
- php - 是否存在在 Laravel 和 Lumen 上测试包的“简单”方法?
- java - $and 在 spring data mongodb 中,最新版本不支持 spEl?(2.2.6)
- node.js - 如何在 NodeJS 中检索通过 API 调用发送的 blob 数据?
- react-native - React-native 简单图像处理
- javascript - 拒绝访问同一域上跨域对象上的属性“文档”的权限
- linux - 如何隐藏ps命令的密码?
- php - 来自不同表的 Laravel 身份验证不起作用