2

リストを構造体のフィールドとして定義するにはどうすればよいですか?

このようなもの :

public struct MyStruct
{
    public decimal SomeDecimalValue;
    public int SomeIntValue;
    public List<string> SomeStringList = new List<string> // <<I Mean this one?
}

そして、その文字列を次のように使用します:

Private void UseMyStruct()
{
     MyStruct S= new MyStruct();
     s.Add("first string");
     s.Add("second string");
}

私はいくつかのことを試しましたが、それらはすべてエラーを返し、機能しません。

4

2 に答える 2

1

構造体のパブリック フィールドは悪であり、見ていないときに背中を刺すことになります。

つまり、次のように (parameterfull) コンストラクターで初期化できます。

public struct MyStruct
{
    public decimal SomeDecimalValue;
    public int SomeIntValue;
    public List<string> SomeStringList;

    public MyStruct(decimal myDecimal, int myInt)
    {
      SomeDecimalValue = myDecimal;
      SomeIntValue = myInt;
      SomeStringList = new List<string>();
    }

    public void Add(string value)
    {
      if (SomeStringList == null)
        SomeStringList = new List<string>();
      SomeStringList.Add(value);
    }
}

SomeStringList誰かがデフォルトのコンストラクターを使用している場合でも、 は null になることに注意してください。

MyStruct s = new MyStruct(1, 2);
s.SomeStringList.Add("first string");
s.Add("second string");

MyStruct s1 = new MyStruct(); //SomeStringList is null
//s1.SomeStringList.Add("first string"); //blows up
s1.Add("second string");
于 2013-10-03T11:47:17.593 に答える