我有两个构造函数,它们将值提供给只读字段。
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;
}
一个构造函数直接接收值,另一个构造函数进行一些计算并获得值,然后设置字段。
现在问题来了:
我不想复制
设置代码。在这种情况下,只有一个
场地已经设置好了,当然还有可能
要大于1。
要使字段为只读,我需要
从构造函数中设置它们,那么
我不能将共享代码“提取”到
效用函数。
我不知道怎么叫
另一个构造函数。
什么好主意吗?
当从基类继承类时,可以通过实例化派生类来调用基类构造函数
class sample
{
public int x;
public sample(int value)
{
x = value;
}
}
class der : sample
{
public int a;
public int b;
public der(int value1,int value2) : base(50)
{
a = value1;
b = value2;
}
}
class run
{
public static void Main(string[] args)
{
der obj = new der(10,20);
System.Console.WriteLine(obj.x);
System.Console.WriteLine(obj.a);
System.Console.WriteLine(obj.b);
}
}
示例程序的输出为
50 10 20
还可以使用此关键字从另一个构造函数调用一个构造函数
class sample
{
public int x;
public sample(int value)
{
x = value;
}
public sample(sample obj) : this(obj.x)
{
}
}
class run
{
public static void Main(string[] args)
{
sample s = new sample(20);
sample ss = new sample(s);
System.Console.WriteLine(ss.x);
}
}
这个示例程序的输出是
20
如果没有初始化方法就不能令人满意地实现你想要的(例如,因为你想在初始化代码之前做太多事情,或者将它包装在try-finally中,或者其他什么),你可以让任何或所有构造函数通过引用初始化例程来传递只读变量,然后该例程将能够随意操作它们。
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);
}
当从基类继承类时,可以通过实例化派生类来调用基类构造函数
class sample
{
public int x;
public sample(int value)
{
x = value;
}
}
class der : sample
{
public int a;
public int b;
public der(int value1,int value2) : base(50)
{
a = value1;
b = value2;
}
}
class run
{
public static void Main(string[] args)
{
der obj = new der(10,20);
System.Console.WriteLine(obj.x);
System.Console.WriteLine(obj.a);
System.Console.WriteLine(obj.b);
}
}
示例程序的输出为
50 10 20
还可以使用此关键字从另一个构造函数调用一个构造函数
class sample
{
public int x;
public sample(int value)
{
x = value;
}
public sample(sample obj) : this(obj.x)
{
}
}
class run
{
public static void Main(string[] args)
{
sample s = new sample(20);
sample ss = new sample(s);
System.Console.WriteLine(ss.x);
}
}
这个示例程序的输出是
20