【发布时间】:2015-12-16 05:01:06
【问题描述】:
我正在编写一个带有成员变量的类。我想为这些字段定义默认值,并且必须能够使用自定义设置值覆盖它们。我想创建某种类或结构来保存这些变量的数据。我希望使用该类的人能够定义所有变量,或者如果他们没有,那么字段将设置为默认值(我将定义)。不确定最干净的方法来做到这一点。这是我的想法,但我不确定我是否可以做得更好:
public class ReportPageParams
{
public float Width { get; private set; }
public float Height { get; private set; }
public float LeftMargin { get; private set; }
public float RightMargin { get; private set; }
public float TopMargin { get; private set; }
public float BottomMargin { get; private set; }
//Constructor
ReportPageParams(float pWidth, pHeight)
{
Width = 52f
Height = 52f
//...
}
}
public class ReportPage
{
//same fields as ReportPageParams plus some more
private float _width, _height;
private float _leftMargin;
private float _rightMargin;
//...
ReportPage(ReportPageParams pCustomParams = null)
{
if (pCustomParams != null)
{
_width = pCustomParams.Width
_height = pCustomParams.Height
//...
}
else
{
//set fields to default values
}
}
}
【问题讨论】:
-
您使用的是什么版本的 C#,您是否在 Visual Studio 2015 中编写代码?如果您有更多选择。
-
public float Width { get; private set; } = 1.222 or something将为属性设置默认值
标签: c# .net class default-constructor