ami*_*min 2 c# asp.net struct list
如何将List定义为struct的字段?
像这样的东西:
public struct MyStruct
{
public decimal SomeDecimalValue;
public int SomeIntValue;
public List<string> SomeStringList = new List<string> // <<I Mean this one?
}
Run Code Online (Sandbox Code Playgroud)
然后使用该字符串像这样:
Private void UseMyStruct()
{
MyStruct S= new MyStruct();
s.Add("first string");
s.Add("second string");
}
Run Code Online (Sandbox Code Playgroud)
我尝试过一些东西,但它们都会返回错误并且不起作用.
Kri*_*ten 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:这不是线程安全的,但可以根据需要进行修改.
| 归档时间: |
|
| 查看次数: |
1812 次 |
| 最近记录: |