c# convert existing class to use properties correctly
我有以下课程:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Given { public string text =""; public List<StartCondition> start_conditions = new List<StartCondition>(); }; class StartCondition { public int index = 0; public string device ="unknown"; public string state ="disconnected"; public bool isPass = false; }; |
我想将它们转换为C属性(使用get;和set;)
看看这个问题:在C中什么是get-set-syntax-in-c,似乎我可以使属性变得很好和简单,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 | class Given { public string text { get; set; } public List<StartCondition> start_conditions { get; set; } }; class StartCondition { public int index { get; set; } public string device { get; set; } public string state { get; set; } public bool isPass { get; set; } }; |
但现在我不知道该如何添加初始化,因为我想要与以前相同的起始值,或者对于列表容器,我希望它是新的。
实现这一目标的最佳方法是什么?
自C 6.0以来,包含自动属性初始值设定项的功能。语法是:
1 | public int X { get; set; } = x; // C# 6 or higher |
使用构造函数。所以你的课应该是这样的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public class StartCondition { public int index { get; set; } public string device { get; set; } public string state { get; set; } public bool isPass { get; set; } // This is the constructor - notice the method name is the same as your class name public StartCondition(){ // initialize everything here index = 0; device ="unknown"; state ="disconnected"; isPass = false; } } |
如果您不使用C 6+(或者即使您使用了C 6+,也可以显式声明属性的支持变量:
1 2 3 4 5 6 7 8 | public class Given { private string _text = string.Empty; private List<StartCondition> _start_conditions = new List<StartCondition>(); public string text { get{ return _text; } set{ _text = value; } } public List<StartCondition> start_conditions { get{ return _start_conditions; } set{ _start_conditions = value; } } } |
这允许您像以前一样设置初始化。
创建一个构造函数以使用默认值启动类实例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | class Given { public Given(){ this.text =""; start_conditions = new List<StartCondition>(); } public string text { get; set; } public List<StartCondition> start_conditions { get; set; } }; class StartCondition { public StartCondition(){ this.index = 0; this.device ="unknown"; this.state ="disconnected"; this.isPass = false; } public int index { get; set; } public string device { get; set; } public string state { get; set; } public bool isPass { get; set; } }; |
现在,您可以使用