now*_*ed. 0 .net c# constructor
我知道我们可以使用构造函数链从其他构造函数调用参数化构造函数.
但,
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);
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎没有调用基础构造函数(没有任何参数).
有任何想法吗 ?
编辑:
当前:打印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();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法呢?
您正在寻找this():
public class T1
{
public T1()
{
Console.WriteLine("t1");
}
public T1(string s) : this()
{
Console.WriteLine(s);
}
}
Run Code Online (Sandbox Code Playgroud)