首页 > 解决方案 > 如何将变量存储在数组中

问题描述

我正在尝试将“序列码”或其他任何内容连接到要打印为字符串的变量。该代码将由 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));
        }
}

标签: c#arraysstringvariables

解决方案


听起来你想要一本字典。键是名称,值是传感器数据。

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

推荐阅读