本文介绍了有没有办法在不使用构造函数的情况下初始化结构的成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含两个列表的 struct
:
I have a struct
that contains two lists:
struct MonthData
{
public List<DataRow> Frontline;
public List<DataRow> Leadership;
}
但是,我想在创建结构时对两者进行初始化.如果我尝试:
However, I want to initialize both when the struct is created. If I try:
struct MonthData
{
public List<DataRow> Frontline = new List<DataRow>();
public List<DataRow> Leadership = new List<DataRow>();
}
然后我得到:
Error 23 'MonthData.Frontline': cannot have instance field initializers in structs
...
由于结构不能有无参数构造函数,我也不能只在构造函数中设置它.到目前为止,我只能看到以下选项:
Since structs cannot have parameterless constructors, I can't just set this in a constructor either. So far, I can only see the following options:
- 在创建 MonthData 实例时初始化这两个属性
- 使用类而不是结构
- 创建一个带参数的构造函数并使用它
- 为初始化它们的属性制作 getter 和 setter懒洋洋的.
推荐的方法是什么?现在,我认为将它作为一个类是最好的主意.
What is the recommended approach for this? Right now, I'm thinking making this a class is the best idea.
推荐答案
你应该使用类来代替.来自 MSDN:
You ought to use a class instead. From MSDN:
一般来说,类用于对更复杂的行为或打算在创建类对象后修改的数据进行建模.结构最适合包含主要数据的小型数据结构,这些数据在结构创建后不会被修改.
这篇关于有没有办法在不使用构造函数的情况下初始化结构的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!