2

我正在寻找在 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";
4

3 回答 3

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]); 
于 2011-06-07T21:42:02.247 回答
1
int[] arr = Enumerable.Range(0, 10).ToArray();

更新

int x=10;
int[] arr = Enumerable.Range(0, x).ToArray();
于 2011-06-07T21:40:55.493 回答
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;}
    }
}  
于 2011-06-07T21:58:41.977 回答