【问题标题】:Can I put readonly strings in an array to iterate over?我可以将只读字符串放入数组中进行迭代吗?
【发布时间】:2016-09-19 08:35:42
【问题描述】:

我的表的很多标题都有很多字符串,例如:

private readonly string headerOne = translateIfNeeded("headerOne");
private readonly string headerTwo = translateIfNeeded("headerTwo");
private readonly string headerThree = translateIfNeeded("headerThree");
private readonly string headerFour = translateIfNeeded("headerFour");

得到了大约 30 个。

我可以简单地将它们分组到一个数组中,以便以后可以轻松地迭代它们吗?试图将以下内容放在我的字符串下方,但它不会让我这样做;

private readonly string[] headers = { headerOne, headerTwo };
private readonly string[] headers = new string[]{ headerOne, headerTwo };

说了一些关于“字段初始值设定项不能引用非静态字段 [...] headerOne”的内容。

【问题讨论】:

  • private static readonly string[] headers = { headerOne, headerTwo };
  • 同样的错误信息。那太容易了,不是吗?
  • 您可以在构造函数中初始化您的 headers 数组:headers = new string[] { headerOne, headerTwo } 并通过 private readonly string[] headers; 简单地声明成员变量
  • 也想过这个,但是我的构造函数会很胖:(
  • 没错,构造函数会很混乱。如果您只使用标头变量,您可以使用反射通过this.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic) 读取所有变量,使用您的翻译函数对其进行初始化并将标头添加到列表中

标签: c# arrays string initialization


【解决方案1】:

您可以使用Dictionary<int, string>Dictionary<string, string>

Dictionary<string, string> headers = new Dictionary<string, string>();
headers.Add("headerOne", translateIfNeeded("headerOne"));
headers.Add("headerTwo", translateIfNeeded("headerTwo"));
headers.Add("headerThree", translateIfNeeded("headerThree"));
headers.Add("headerFour", translateIfNeeded("headerFour"));

您可以对其进行迭代或(标准方式)通过键访问值:

string headerTwo = headers["headerTwo"];

如果您需要只读字典,4.5 版以后就有了:

ReadOnlyDictionary&lt;TKey, TValue&gt; Class

【讨论】:

  • 好主意。如果这个特定问题的答案没有及时出现,将标记为解决方案。
  • 只读的东西实际上是为了更多的常数,让系统在内部整齐地排序东西。 AFAIK 常量有一个单独的内存区域。这里有什么优化技巧吗?
  • 您不必担心这些微优化。如果该字段是不变的常量,则使用const; 如果不是,请不要。在这种情况下,它不能是一个常数。
【解决方案2】:

根据Static readonly string arrays,即使它使用静态:

public readonly ReadOnlyCollection<string> headers = new ReadOnlyCollection<string>(
  new string[] {
    headerOne,
    headerTwo,
    headerThree,
  }
);

供参考:ReadOnlyCollection(T) Class (System.Collections.ObjectModel)C# ReadOnlyCollection Tips - Dot Net Perls

【讨论】:

    【解决方案3】:

    您可以定义一个列表添加所有标题并轻松迭代它们,简单示例:

            List<string> headersList = new List<string>();
            headersList.AddRange(new string[] { headerOne, headerTwo, headerThree, headerFour });
    
            foreach (string header in headersList)
            {
                Console.WriteLine(header);
            }
            Console.ReadLine();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2015-04-09
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2020-08-04
      • 1970-01-01
      相关资源
      最近更新 更多