我有一个struct包含两个列表:
struct MonthData
{
public List<DataRow> Frontline;
public List<DataRow> Leadership;
}
Run Code Online (Sandbox Code Playgroud)
但是,我想在创建结构时初始化它们.如果我尝试:
struct MonthData
{
public List<DataRow> Frontline = new List<DataRow>();
public List<DataRow> Leadership = new List<DataRow>();
}
Run Code Online (Sandbox Code Playgroud)
然后我得到:
Error 23 'MonthData.Frontline': cannot have instance field initializers in structs
...
Run Code Online (Sandbox Code Playgroud)
由于结构不能有无参数构造函数,我不能只在构造函数中设置它.到目前为止,我只能看到以下选项:
推荐的方法是什么?现在,我在想这个课程是最好的主意.
如果您只是询问语法...尝试构建和使用静态工厂...通常,结构应该用于不可变的东西,而工厂(调用私有构造函数)是一种更好的方法对于不可变类型而不是使用公共构造函数.
struct MonthData
{
public List<DataRow> Frontline;
public List<DataRow> Leadership;
private MonthData(List<DataRow> frontLine = null,
List<DataRow> leadership = null)
{
Frontline = frontLine?? new List<DataRow>();
Leadership = leadership?? new List<DataRow>();
}
public static MonthData Factory(
List<DataRow> frontLine= null,
List<DataRow> leadership= null)
{ return new MonthData(frontLine, leadership); }
}
Run Code Online (Sandbox Code Playgroud)