代码是什么:base() [英] What is the code : base()

查看:59
本文介绍了代码是什么:base()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码中 base()的目的是什么?

What is the purpose of base() in the following code?

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


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


Why At design time messages are displayed ؟

我的代码:

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

推荐答案

base()是对 myTextBox ,恰好是 TextBox .请注意,此基本构造函数将在派生类中构造函数主体执行之前 执行.

base() in your code is a call to the parameterless constructor of the base-class ofmyTextBox, which happens to beTextBox. Note that this base constructor will execute before the execution of the body of the constructor in the derived class.

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

Every class's constructor must eventually call one of its base class's constructors, either directly or through chained constructors in the same class. Consequently, there is always an implicit / explicit base(...) or explicit this(...) call on every constructor declaration. If it is omitted, there an implicit call to base(), i.e. the parameterless constructor of the base class (this means that the call tobase()in your example is redundant). Whether such a declaration compiles or not depends on whether there exists such an accessible constructor in the base class.

编辑:两个要点:

  1. 类层次结构的根没有基类,因此此规则不适用于 System.Object 的唯一构造函数.
  2. 第一句话应为:"成功完成的每个非 System.Object 类的构造函数都必须最终调用其基类的一个构造函数构造函数."这是一个从头到尾"的示例,其中从来没有调用基类的构造函数:实例化此类的对象显然会导致执行堆栈溢出.
  1. The root of the class-hierarchy does not have a base class, so this rule does not apply to System.Object's only constructor.
  2. The first sentence should read: "every non-System.Object class's constructor that completes successfully must eventually call one of its base class's constructors." Here is a 'turtles all the way down' example where the base class's contructor is never called: instantiating an object of such a class will obviously overflow the execution-stack.


// 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
    }
}

这篇关于代码是什么:base()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆