【问题标题】:How can I store a variable in an array如何将变量存储在数组中
【发布时间】:2020-03-12 17:00:50
【问题描述】:

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

【问题讨论】:

  • 也许你想要一本字典。键是名称,值是传感器数据。
  • 您要保留变量的值还是变量本身? (您是否需要能够在仅给定字符串s123 的情况下更改名为s123 的变量的值?)在这种情况下,可能首先将它们存储在局部变量中是一个糟糕的选择。也许字典应该是存储这些东西的官方场所。

标签: c# arrays string variables


【解决方案1】:

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

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

【讨论】:

  • 这正是我想要的!非常感谢! :D
  • 可能要考虑使用string doThis = $"s{sensorValue}"; 来利用插值字符串。
猜你喜欢
  • 2018-02-08
  • 1970-01-01
  • 2023-03-23
  • 2010-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-08
  • 2019-11-29
相关资源
最近更新 更多