C#转换现有的类以正确使用属性 [英] c# convert existing class to use properties correctly
本文介绍了C#转换现有的类以正确使用属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下课程:
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;)
I want to convert them into c# properties (using get; and set;)
看着这个问题: -is-the-get-set-syntax-in-c ,看来我可以像这样使一个属性变得好看又简单:
Looking at this question: what-is-the-get-set-syntax-in-c, it seems I can make a property nice and easy like this:
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; }
};
但是现在我不知道应该如何添加初始化,因为我想要相同的起始值
But now I don't know how I should add my initialisations, because I want the same start values as I had before, or for the List container I want it to be new'ed.
像以前一样,或者对于List容器,我希望它是新的。
What is the best way to achieve this?
推荐答案
自C#6.0起,具有自动属性初始化程序的功能。语法为:
The ability to have auto property initializers is included since C# 6.0. The syntax is:
public int X { get; set; } = x; // C# 6 or higher
这篇关于C#转换现有的类以正确使用属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文