初始化Struct内部的数组(字符串或任何其他数据类型)

本文关键字:任何 其他 数据类型 字符串 Struct 内部 数组 初始化 | 更新日期: 2023-09-27 17:58:31

我希望在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";

初始化Struct内部的数组(字符串或任何其他数据类型)

首先,您的代码几乎可以工作:

int[] array = new int[10]; // This is the only line that needs changing  
for (int i=0; i < 10; i++) 
    array[i] = i; 

您可以通过添加自定义构造函数来初始化结构中的数组,然后在创建结构时通过调用构造函数来初始化它。这是一个类所必需的。

话虽如此,我强烈建议在这里使用类,而不是结构。可变结构是个坏主意,而包含引用类型的结构也是个坏主意。


编辑:

如果你试图制作一个长度是动态的集合,你可以使用List<T>而不是数组:

List<int> list = new List<int>();
for (int i=0; i < 10; i++) 
    list.Add(i);
// To show usage...
Console.WriteLine("List has {0} elements.  4th == {1}", list.Count, list[3]); 
int[] arr = Enumerable.Range(0, 10).ToArray();

更新

int x=10;
int[] arr = Enumerable.Range(0, x).ToArray();
// IF you are going to use a struct
public struct Structure1
{
    readonly string String1;
    readonly string[] stringArr;
    readonly List<string> myList;
    public Structure1(string String1)
    {
        // all fields must be initialized or assigned in the 
        // constructor

        // readonly members can only be initialized or assigned
        // in the constructor
        this.String1 = String1
        // initialize stringArr - this will also make the array 
        // a fixed length array as it cannot be changed; however
        // the contents of each element can be changed
        stringArr = new string[] {};
        // if you use a List<string> instead of array, you can 
        // initialize myList and add items to it via a public setter
        myList = new List<string>();
    }
    public List<string> StructList
    {
        // you can alter the contents and size of the list
        get { return myList;}
    }
}  
相关文章: