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

13

结构中不能有字段初始值设定项。

原因是字段初始值设定项确实被编译到无参数构造函数中,但结构中不能有无参数构造函数。

不能有无参数构造函数的原因是结构的默认构造是用零字节擦除其内存。

但是,您可以这样做:

public struct MyStruct
{
    private List<string> someStringList;

    public List<string> SomeStringList
    {
         get
         {
             if (this.someStringList == null)
             {
                 this.someStringList = new List<string>();
             }

             return this.someStringList;
         }
    }
}

注意:这不是线程安全的,但可以根据需要进行修改。

于 2013-10-03T11:41:26.490 回答
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 回答