【问题标题】:How to have a string array which mostly acts as a single string?如何拥有一个主要用作单个字符串的字符串数组?
【发布时间】:2021-10-15 20:16:29
【问题描述】:

在我的项目中,我有一个类(可能有多个派生),其中一个字段是一个字符串。

我们还有实例化这个类的许多对象的代码(出于技术原因,每个实例的代码分开)。所以代码文件可能会很长。

大多数情况下都可以。但在极少数情况下,我需要一个字符串数组作为 TestValue。我知道我可以将其声明为string[]。但是由于通常我们只分配单个字符串,因此当只需要单个字符串时,最好不必总是在代码中显式创建数组,如下所示:

public class Datapoint
{
    public uint Id;

    public string[] TestValue;
}

public void CreateEntries()
{
   Table.Add(new Datapoint { Id = 1, TestValue = "123" });
   Table.Add(new Datapoint { Id = 2, TestValue = "12.9" });
   Table.Add(new Datapoint { Id = 3, TestValue = "Enabled" });
   Table.Add(new Datapoint { Id = 4, TestValue = "Temperature" });
   Table.Add(new Datapoint { Id = 5, TestValue = { "12.3", "9.8", "7.3" } });
}

有什么想法吗? 谢谢!

【问题讨论】:

  • 添加第二个属性,它是一个字符串。当您设置两个属性之一时,清除另一个。
  • 已经尝试将浮点值存储到字符串中是个坏主意

标签: c# arrays string implicit-conversion


【解决方案1】:

您可以使用params 选项创建构造函数:

public class Datapoint
{
    public uint Id;

    public string[] TestValue;

    public Datapoint(uint id, params string[] testValue)
    {
        Id = id;
        TestValue = testValue;
    }
}

用法是:

Table.Add(new Datapoint(1, "123"));
Table.Add(new Datapoint(2, "12.9"));
Table.Add(new Datapoint(3, "Enabled"));
Table.Add(new Datapoint(4, "Temperature"));
Table.Add(new Datapoint(5, "12.3", "9.8", "7.3"));

【讨论】:

  • 移动到构造函数还可以让您拥有多个重载 -- stringstring[] -- 如果这变得有用的话
猜你喜欢
  • 2015-05-14
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-22
  • 2013-06-07
  • 2011-07-24
相关资源
最近更新 更多