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 に答える