.jpg)
我有两个构造函数,它们将值馈送到只读字段。
public class Sample
{
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
_intField = i;
}
public Sample(int theInt) => _intField = theInt;
public int IntProperty => _intField;
private readonly int _intField;
}
一个构造函数直接接收值,另一个构造函数执行一些计算并获取值,然后设置字段。
现在这里有一个问题:
有什么想法吗?

网友回答:
在构造函数的主体之前,请使用:
: base (parameters)
: this (parameters)
例:
public class People: User
{
public People (int EmpID) : base (EmpID)
{
// Add more statements here.
}
}

网友回答:
喜欢这个:
public Sample(string str) : this(int.Parse(str)) { }

网友回答:
如果你想要的东西不能令人满意地实现,而不用它自己的方法进行初始化(例如,因为你想在初始化代码之前做太多事情,或者把它包装在try-final中,或者其他什么),你可以让任何或所有构造函数通过引用将只读变量传递给初始化例程,然后初始化例程将能够随意操作它们。
public class Sample
{
private readonly int _intField;
public int IntProperty => _intField;
private void setupStuff(ref int intField, int newValue) => intField = newValue;
public Sample(string theIntAsString)
{
int i = int.Parse(theIntAsString);
setupStuff(ref _intField,i);
}
public Sample(int theInt) => setupStuff(ref _intField, theInt);
}
模板简介:该模板名称为【我不知道如何从另一个构造函数调用一个构造函数】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。