从C#中的参数化构造函数调用无参数构造函数
本文关键字:参数 函数调用 构造函数 | 更新日期: 2023-09-27 17:59:27
我知道我们可以使用构造函数链接从其他构造函数调用参数化构造函数。
但是,
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
var t1 = new T1("t2");
}
}
public class T1
{
public T1()
{
Console.WriteLine("t1");
}
public T1(string s):base()
{
Console.WriteLine(s);
}
}
这似乎没有调用基构造函数(没有任何参数)。
有什么想法吗?
编辑:
当前:打印t2。t1不在控制台上。
因此,我采用了以下方法:
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
var t1 = new T1("t2");
}
}
public class T1
{
private void privateMethod()
{
Console.WriteLine("common method");
}
public T1()
{
privateMethod();
}
public T1(string s):base()
{
Console.WriteLine(s);
privateMethod();
}
}
有更好的方法吗?
您正在寻找this()
:
public class T1
{
public T1()
{
Console.WriteLine("t1");
}
public T1(string s) : this()
{
Console.WriteLine(s);
}
}
如果要查找关键字this
,base
将调用父类(就像在扩展的类中一样)。
使用base
关键字时,实际上是在调用Object()
构造函数。您想要使用this
关键字
public class T1
{
public T1()
{
Console.WriteLine("t1");
}
public T1(string s) : this()
{
Console.WriteLine(s);
}
}
如其他答案中所述,要调用无参数构造函数,必须使用:this()
(base()
调用基类的无参数构造函数)
然而,我认为这是一种不好的做法。带有参数的构造函数是更好地定义类初始化的构造函数,因此,无参数构造函数应该调用它,而不是反之亦然。
即:
public class T1
{
public T1():this(String.Empty) // <= calling constructor with parameter
{
Console.WriteLine("t1");
}
public T1(string s)
{
Console.WriteLine(s);
}
}
而不是:
public class T1
{
public T1()
{
Console.WriteLine("t1");
}
public T1(string s) : this() // <= calling parameterless constructor
{
Console.WriteLine(s);
}
}
顺便说一句,该语言似乎正在鼓励使用主构造函数,使用,嗯-主构造函数(这是C#6中的一个实验功能,被删除了,不确定是否是好的…)
this
调用当前类实例,而base
调用父类实例。