c#将现有类转换为正确使用属性

时间:2016-11-07 17:43:29

标签: c# properties containers

我有以下课程:

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;)

看看这个问题:what-is-the-get-set-syntax-in-c,似乎我可以像这样做一个好看又容易的财产:

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; }
};

但现在我不知道应该如何添加我的初始化,因为我想要与之前相同的起始值,或者对于List容器我希望它是新的。

实现这一目标的最佳方法是什么?

4 个答案:

答案 0 :(得分:6)

自C#6.0以来,包含自动属性初始值设定项的功能。语法是:

public int X { get; set; } = x; // C# 6 or higher

答案 1 :(得分:4)

使用构造函数。所以你的课程看起来像这样:

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;
  }
}

答案 2 :(得分:0)

创建一个构造函数,以使用默认值

启动您的类实例
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; }
};

现在,您可以使用StartCondition A = new StartCondition();

创建具有默认值的实例

答案 3 :(得分:0)

如果您没有使用C#6+(或者即使您是),您可以显式声明属性的支持变量:

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; } }
}

这允许您像以前一样设置初始化。