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

时间:2011-06-07 21:38:20

标签: c# arrays string struct dynamic-arrays

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

3 个答案:

答案 0 :(得分:3)

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

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]); 

答案 1 :(得分:1)

int[] arr = Enumerable.Range(0, 10).ToArray();

<强>更新

int x=10;
int[] arr = Enumerable.Range(0, x).ToArray();

答案 2 :(得分:0)

// 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;}
    }
}