初始化 Struct 内的数组(字符串或任何其他数据类型)
我想用 C# 来做这件事。
public struct Structure1
{ string string1 ; //Can be set dynamically
public string[] stringArr; //Needs to be set dynamically
}
一般来说,如果需要,应该如何动态初始化数组? 简而言之,我试图在 C# 中实现这一点:
int[] array;
for (int i=0; i < 10; i++)
array[i] = i;
另一个例子:
string[] array1;
for (int i=0; i < DynamicValue; i++)
array1[i] = "SomeValue";
I'm looking to do this in C#.
public struct Structure1
{ string string1 ; //Can be set dynamically
public string[] stringArr; //Needs to be set dynamically
}
In general, how should one initialize an array dynamically if need be?
In simplest of terms, I'm trying to achieve this in C#:
int[] array;
for (int i=0; i < 10; i++)
array[i] = i;
Another example:
string[] array1;
for (int i=0; i < DynamicValue; i++)
array1[i] = "SomeValue";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,您的代码几乎可以工作:
您可以通过添加自定义构造函数来初始化结构中的数组,然后在创建结构时调用构造函数来初始化它。这对于课堂来说是必需的。
话虽这么说,我强烈建议在这里使用类而不是结构。可变结构是一个坏主意 - 包含引用类型的结构也是一个非常坏的主意。
编辑:
如果您尝试创建长度动态的集合,则可以使用
List
而不是数组:First off, your code will almost work:
You could potentially initialize your arrays within your struct by adding a custom constructor, and then initialize it calling the constructor when you create the struct. This would be required with a class.
That being said, I'd strongly recommend using a class here and not a struct. Mutable structs are a bad idea - and structs containing reference types are also a very bad idea.
Edit:
If you're trying to make a collection where the length is dynamic, you can use
List<T>
instead of an array:更新
update