【问题标题】:How to define a list in struct in asp c#?如何在asp c#的struct中定义一个列表?
【发布时间】:2013-10-03 11:33:53
【问题描述】:

如何将 List 定义为 struct 的字段?

类似这样的:

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");
}

我尝试了一些方法,但它们都返回错误并且不起作用。

【问题讨论】:

  • 为什么不用class 而不是struct
  • 你可以随时使用s.SomeStringList.Add();
  • 好的,我可以,但我不能在结构中定义列表。这是我的问题。不使用 s.Add()。请仔细阅读帖子。如果您确定,请尝试此代码
  • @sine 和@SWeko:当字符串列表无法初始化时,这将如何工作?它不能......它会抛出一个NullRef。 OP 必须在实例化结构后初始化列表。
  • 你完全正确,忽略了我的耻辱......

标签: c# asp.net list struct


【解决方案1】:

您不能在结构中包含字段初始值设定项。

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

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

但是,您可以这样做:

public struct MyStruct
{
    private List<string> someStringList;

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

             return this.someStringList;
         }
    }
}

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

【讨论】:

  • 打败我。有一个 +1。
【解决方案2】:

结构中的公共字段是邪恶的,当你不注意时会在背后捅你一刀!

也就是说,你可以在 (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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多