2013-10-03 43 views
2

我该如何定义一个List作为结构体的字段?如何在asp c#中的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"); 
} 

我已经尝试了一些东西,但他们都回传失误和不工作。

+2

为什么

也就是说,你可以在(parameterfull)构造函数初始化它,像这样你不用''而不是'struct'吗? –

+8

你总是可以使用's.SomeStringList.Add()'; – SWeko

+0

好吧,我可以,但我不能定义列表结构.. 这是我的问题..不使用s.Add().. 请仔细阅读这篇文章。 如果您确定,请尝试下面的代码 – amin

回答

12

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

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

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

但是,你可以做的是这样的:

public struct MyStruct 
{ 
    private List<string> someStringList; 

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

      return this.someStringList; 
     } 
    } 
} 

注:这是不是线程安全的,但它可以被修改为如果需要的话。

+0

打败我吧。有+1。 –

+0

@SimonWhitehead谢谢:-) –

+0

非常感谢您的描述... – amin

1

结构中的公共领域是邪恶的,当你不在寻找的时候会刺伤你!如果有人使用默认的构造函数

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仍然将是无效:

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"); 
相关问题