中初始化结构数组

中初始化结构数组

本文介绍了在 C# 中初始化结构数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 如何尽可能清晰地初始化结构体的常量/静态数组?How can I initialize a const / static array of structs as clearly as possible?class SomeClass{ struct MyStruct { public string label; public int id; }; const MyStruct[] MyArray = { {"a", 1} {"b", 5} {"q", 29} };};推荐答案首先,你真的必须有一个可变结构吗?他们几乎总是一个坏主意.同样是公共领域.在某些非常偶然的情况下,它们是合理的(通常将两个部分放在一起,如 ValueTuple),但在我的经验中它们非常罕见.Firstly, do you really have to have a mutable struct? They're almost always a bad idea. Likewise public fields. There are some very occasional contexts in which they're reasonable (usually both parts together, as with ValueTuple) but they're pretty rare in my experience.除此之外,我只需要创建一个构造函数来获取两位数据:Other than that, I'd just create a constructor taking the two bits of data:class SomeClass{ struct MyStruct { private readonly string label; private readonly int id; public MyStruct (string label, int id) { this.label = label; this.id = id; } public string Label { get { return label; } } public string Id { get { return id; } } } static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct> (new[] { new MyStruct ("a", 1), new MyStruct ("b", 5), new MyStruct ("q", 29) });}注意使用 ReadOnlyCollection 而不是公开数组本身 -这将使它不可变,避免问题直接暴露数组.(代码显示确实初始化了一个结构数组 - 然后它只是将引用传递给 ReadOnlyCollection 的构造函数.)Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly. (The code show does initialize an array of structs - it then just passes the reference to the constructor of ReadOnlyCollection<>.) 这篇关于在 C# 中初始化结构数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-21 19:32