c# - 如何将变量存储在数组中
问题描述
我正在尝试将“序列码”或其他任何内容连接到要打印为字符串的变量。该代码将由 5 个传感器生成,并将给我一个 5 位数字 (sensorValue)(此计算未包含在示例中,我已将其简化为 3 位)。我在代码前添加了一个“s”,这样我就可以创建一个同名的变量。但是,当我收到变量已分配但从未使用过的消息时,我似乎无法在数组中存储变量。至少它显然不能以我正在做的方式附加。但我希望我能说明我打算做什么。
所以我得到了“序列码”s123,但我需要将它转换为另一个字符串。将有大约 3000 个不同的“序列号”,每个序列号都附有一个字符串。我确信我可以做出 3000 个“if”语句,但我担心这会很慢。
有什么想法可以克服我的这个问题吗?
提前致谢!
using System;
using System.Linq;
namespace TestingArray
{
static void Main(string[] args)
{
// Trying to assign a value to the string that is used in the array
var s123 = "Hello";
var s321 = "Bye";
var s111 = "Thanks";
// Creating the array to be used
object [] arr = { "s123", "s321", "s111" };
// A simulation of what the future sensor would read
int sensorValue;
sensorValue = 123;
// Creating a "code" with the sensorValue to find it in the array.
string doThis = "s" + sensorValue
;
// I want to display the string which corresponds to this "serial-code" string.
Console.Write(arr.Contains(doThis));
}
}
解决方案
听起来你想要一本字典。键是名称,值是传感器数据。
static void Main(string[] args)
{
Dictionary<string, string> sensors = new Dictionary<string, string> {
{"s123", "Hello"},
{"s321", "Bye"},
{"s111", "Thanks"}
};
// A simulation of what the future sensor would read
int sensorValue;
sensorValue = 123;
// Creating a "code" with the sensorValue to find it in the array.
string doThis = "s" + sensorValue;
if (sensors.ContainsKey(doThis)) {
Console.WriteLine(sensors[doThis]);
}
}
推荐阅读
- javascript - 在 angularjs 中使用 ng-pattern 时浏览器挂起
- javascript - Navigator.getGamepads() 不会返回相同类型游戏手柄的不同实例
- python - 数据流作业一直显示“开始”
- angular - 如何防止我导入的模块覆盖我的路由?
- wordpress - Wordpress:重命名工具栏链接
- python-3.x - 在 Python 中从字符串中删除除句点 (.) 和冒号 (:) 之外的所有标点符号
- python - 按条件将列拆分为多行
- javascript - 将 RTF 格式转换为 HTML JavaScript
- vue.js - 上传后如何在裁剪器中加载占位符
- pandas - 将 SKLearn 回归系数写入 Pandas 系列