我有这段代码:
public struct SmartFilter
{
public int from, to;
public ArrayList collect = new ArrayList();
public long bit;
}
我得到错误:
cannot have instance field initializers in structs
我尝试了不同的方法来克服这个错误但没有成功,
如何在结构/类中有一个数组列表?
最佳答案
这里有多个问题:
- 有一个可变的结构 - 只是邪恶
- 有公共(public)领域
- 使用
ArrayList
这些都不能帮助你......
对于 class
初始化器可以正常工作
使用一个属性你可以做惰性初始化:
public ArrayList Collect {
get { return collect ?? (collect = new ArrayList()); }
}
我会重构为:
public class SmartFilter
{
public int From {get;set;}
public int To {get;set;}
private List<SomeKnownType> collect = new List<SomeKnownType>();
public List<SomeKnownType> Collect { get { return collect; } }
public long Bit {get;set;}
}
关于c# struct/class initilaze 一个 Arraylist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4623516/