C#类的构造函数默认值的问题 [英] C# Class constructor default value question
本文介绍了C#类的构造函数默认值的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下类:
public class Topic
{
public string Topic { get; set; }
public string Description { get; set; }
public int Count { get; set; }
}
我想有始终设置为零时开始计数的类
I would like to have the Count always set to zero when the class is created with the following:
var abc = new Topic {
Topic = "test1",
Description = "description1"
}
我有点困惑与构造。这是可能的,或者我需要指定主题,描述当我创建ABC算什么?
I am a bit confused with constructor. Is this possible or do I need to specify Topic, Description and Count when I create abc?
推荐答案
您有几个不同的选择
1) INT
默认为零所以这将是零,如果你不进行初始化。
1) int
defaults to zero so it will be zero if you dont initialize it.
2),您可以使用构造
2) you can use a constructor
public Topic(){ Count = 0;}
3)您可以使用支持字段,而不是自动财产和初始化为零
3) You can use a backing field instead of auto-property and initialize that to zero
private int _count = 0;
public int Count {
get {return _count}
set {_count = value; }
}
这篇关于C#类的构造函数默认值的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文