简体   繁体   English

从框架控件继承时,应该调用基本构造函数吗?

[英]When inheriting from a framework control, should I call the base constructor?

I'm inheriting from a ListBox. 我从一个ListBox继承。 Do I need to explicitly call the base constructor? 我是否需要显式调用基本构造函数?

public class MyListBox : ListBox
{
   public MyListBox() : base()
   {
   }

   // or 

   public MyListBox()
   {
   }
}

The two options you listed will compile to identical code. 您列出的两个选项将编译为相同的代码。

The only reason to include : base() is to explicitly denote that you are calling the base classes default constructor instead of some other constructor, by design. 包括: base()的唯一原因是明确表示您是在设计中调用基类的默认构造函数,而不是其他某些构造函数。 If left off, this happens automatically. 如果不设置,此操作将自动发生。 As such, this is completely optional. 因此,这是完全可选的。

However, if you want to use a constructor other than the parameterless constructor of the base class, you would have to explicitly state this, ie: 但是,如果要使用基类的无参数构造函数以外的构造函数,则必须明确声明这一点,即:

public MyListBox() : base("Foo")
{ }

This would explicitly use a constructor which accepted a string as an argument. 这将显式使用接受字符串作为参数的构造函数。

A call of the default constructor is performed implicitly if you do not specify which constructor to call. 如果您未指定要调用的构造函数,则隐式执行默认构造函数的调用。 When you omit a constructor call, C# will call the default one for you; 省略构造函数调用时,C#将为您调用默认的调用。 if there is no default constructor, your code would not compile. 如果没有默认构造函数,则您的代码将无法编译。

10.11.1 Constructor initializers 10.11.1构造函数初始化器

All instance constructors (except those for class object) implicitly include an invocation of another instance constructor immediately before the constructor-body. 所有实例构造函数(类对象除外)都隐式地在构造函数体之前隐含了另一个实例构造函数的调用。

[...] [...]

If an instance constructor has no constructor initializer, a constructor initializer of the form base() is implicitly provided. 如果实例构造函数没有构造函数初始值设定项,则会隐式提供base()形式的构造函数初始值设定项。

According to the C# spec, the two code snippets from your question are equivalent to each other. 根据C#规范,问题中的两个代码段彼此等效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM