public class A{
public int num{get;set;} ;
pubic A(){ num = 1;}
public A(int n)
{
num = n;
}
}public class B : A
{
public B(int n):base(n){}
public B(string n):this(int.Parse(n)){}
public B(string n)
{
new B(int.Parse(n));
}
}红色标注的两个构造函数,有什么区别,以及为什么。
今天在写代码时出现了这个问题,不能解,特来求助
public B(string n)
{
new B(int.Parse(n));
}接上面,居然没有变红色
你查下串联构造函数吧
public Employee(int weeklySalary, int numberOfWeeks)
: this(weeklySalary * numberOfWeeks)
{
}
上一示例中对 this 关键字的使用导致此构造函数被调用:C# 复制代码
public Employee(int annualSalary)
{
salary = annualSalary;
}
public B(string n):this(int.Parse(n)){}
public B(string n)
{
new B(int.Parse(n));
}
这一个是直接调用基类的构造函数;而 public B(string n){new B(int.Parse(n));}
是通过这一个构造函数public B(int n):base(n){},再去调用基类的构造函数,只是比上面的多绕下弯而已。
这只是我的个人见解,欢迎指正
namespace WinFormPic
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
} private void Form2_Load(object sender, EventArgs e)
{
B b = new B("4");
}
} public class A
{
public int Num { get; set; } public A()
{
Num = 1;
} public A(int n)
{
Num = n;
} public A(string n)
{
Num = int.Parse(n);
}
} public class B : A
{
public B()
: base()
{
} public B(int n)
: base(n)
{
} //public B(string n)
// : this(int.Parse(n))
//{
//} public B(string n)
{
new B(int.Parse(n));
}
}
}
在这里设断点 B b = new B("4");然后用f11调试,观看Num的值,就会发现不一样,
只是我找不出原因来解试为什么
在当前实例以外创建了一个新的 B 实例,而当前实例并没有被 n 参数初始化。
因为,参数 n 被传递给了另外的 B 实例。
是调用基类中的构造函数,并将n赋值给基类中构造函数的参数
public B(string n)
{
new B(int.Parse(n));
}
这一个直接初始化B对象