【问题标题】:What is difference between `this` and `base` in the following statement?以下语句中的 `this` 和 `base` 有什么区别?
【发布时间】:2015-06-27 12:05:52
【问题描述】:

以下语句中thisbase键功能有什么区别?

public Customer(string name, string referrerName) : base(name)

public Customer(string Name) : this(Name)

【问题讨论】:

    标签: c# .net inheritance constructor


    【解决方案1】:

    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”

    【讨论】:

      【解决方案2】:
      public Customer(string name, string referrerName) : base(name) 
      

      当客户构造函数调用基构造函数时,第二个例子没有意义,它看起来像构造函数调用本身......

      【讨论】:

      • 承包商?也许是构造函数?
      猜你喜欢
      • 2012-11-20
      • 1970-01-01
      • 2010-11-06
      • 2011-04-12
      • 2011-04-10
      • 1970-01-01
      • 1970-01-01
      • 2013-08-09
      相关资源
      最近更新 更多