【发布时间】:2015-06-27 12:05:52
【问题描述】:
以下语句中this和base键功能有什么区别?
public Customer(string name, string referrerName) : base(name)
public Customer(string Name) : this(Name)
【问题讨论】:
标签: c# .net inheritance constructor
以下语句中this和base键功能有什么区别?
public Customer(string name, string referrerName) : base(name)
public Customer(string Name) : this(Name)
【问题讨论】:
标签: c# .net inheritance constructor
base(name) 将使用提供的参数调用父类构造函数
this(name) 将使用提供的参数调用当前类构造函数,在你的情况下是当前构造函数,并给你一个编译错误,因为构造函数不能调用自己。
假设你有这些类
public class A
{
public A(string a) { Console.WriteLine(a); }
public A(int a) { Console.WriteLine(a * a); }
}
public class B : A
{
public B(string a): base (a) { }
public B(int a): this (a.ToString()) { }
}
new B("hello") 将调用public A(string a) 并在输出中打印“hello”
new B(4) 将调用 public B(string a),后者将调用 public A(string a) 并在输出中打印“4”
【讨论】:
public Customer(string name, string referrerName) : base(name)
当客户构造函数调用基构造函数时,第二个例子没有意义,它看起来像构造函数调用本身......
【讨论】: