【问题标题】:What is the code : base()代码是什么:base()
【发布时间】:2011-04-23 09:16:05
【问题描述】:

下面代码中base()的作用是什么?

class mytextbox : TextBox
{
    public mytextbox() : base()
    {
        this.Text = "stack";
    }
} 

为什么在设计时显示消息?

我的代码:

 class Class1:TextBox 
{
 public Class1()
 {
     this.Resize += new EventHandler(Class1_Resize);
 }
  void Class1_Resize(object sender, EventArgs e)
  {
      MessageBox.Show("Resize");
  }
}

【问题讨论】:

    标签: c# class inheritance constructor default-constructor


    【解决方案1】:

    您的代码中的base() 是对myTextBox 基类的无参数构造函数的调用,它恰好是TextBox。请注意,此基础构造函数将在派生类中执行构造函数主体之前执行

    每个类的构造函数都必须最终调用其基类的构造函数之一,要么直接调用,要么通过同一个类中的链式构造函数调用。因此,在 every 构造函数声明上总是存在隐式/显式 base(...) 或显式 this(...) 调用。如果省略,则会隐式调用base(),即基类的无参数构造函数(这意味着在您的示例中对base() 的调用是多余的)。这样的声明是否编译取决于基类中是否存在这样的 accessible 构造函数。

    编辑: 琐碎的两点:

    1. 类层次结构的根没有基类,因此该规则不适用于System.Object 的唯一构造函数。
    2. 第一句应为:“每个成功完成的非System.Object类的构造函数都必须最终调用其基类的构造函数。”这是一个“从头到尾乌龟”的例子,其中基类的构造函数永远不会被调用:实例化这样一个类的对象显然会溢出执行堆栈。

    // Contains implicit public parameterless constructor
    public class Base { } 
    
    // Does not contain a constructor with either an explicit or implicit call to base()
    public class Derived : Base
    {
        public Derived(int a)
            : this() { }
    
        public Derived()
            : this(42) { }
    
        static void Main()
        {
            new Derived(); //StackOverflowException
        }
    }
    

    【讨论】:

    • 所以在我的例子中不需要?
    • @mystack:不,这是多余的。
    【解决方案2】:

    不知道,没必要。构造函数总是自动调用基类构造函数,而无需您显式编写它。但这就是它的意思。如果您不想调用无参数构造函数,而是调用带参数的构造函数,则必须编写它。

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-08-11
      • 2011-11-14
      相关资源
      最近更新 更多