构造函数定义中的这个冒号是什么? [英] What is this colon in a constructor definition called?
问题描述
在 C# 中定义构造函数时,您可以使用冒号(如本示例):
When defining a constructor in C#, you can use a colon (as in this example):
public class Custom : OtherClass {
public Custom(string s) : base(s) { }
}
这个冒号叫什么? (在不知道它叫什么的情况下很难阅读它.)
请注意,我问的是构造函数定义中的冒号,而不是类定义中显示继承的冒号.
Note that I'm asking about the colon in the constructor definition, not the one showing inheritance in the class definition.
推荐答案
那不是方法定义,而是构造函数定义;冒号用于指定必须在子类的构造函数之前调用的超类构造函数调用.
That isn't a method definition, it's a constructor definition; the colon is used to specify the superclass constructor call which must be called prior to the subclass's constructor.
在 Java 中,使用了 super
关键字,但它必须是子类构造函数中的第一个操作,而 C# 使用的语法更接近 C++ 的初始化列表.
In Java, the super
keyword is used but it must be the first operation in a subclass constructor, whereas C# uses a syntax closer to C++'s initializer lists.
如果子类的超类"构造函数没有任何参数,则不需要显式调用父构造函数,只有在需要参数或要调用特定重载构造函数时,才必须使用此语法.
If a subclass' superclass' constructor does not have any parameters then an explicit call to the parent constructor is not necessary, it is only when arguments are required or if you want to call a specific overloaded constructor must you use this syntax.
Java:
public class Derived extends Parent {
public Derived(String x) {
super(x);
}
}
C#:
public class Derived : Parent {
public Derived(String x) : base(x) {
}
}
更新
C# 语言规范 5.0 - https://msdn.microsoft.com/en-us/library/ms228593.aspx?f=255&MSPPError=-2147217396 在第 10.11.1 节构造函数初始值设定项"
Update
The C# Language Specification 5.0 - https://msdn.microsoft.com/en-us/library/ms228593.aspx?f=255&MSPPError=-2147217396 has an explanation in section 10.11.1 "Constructor initializers"
所有实例构造函数(除了那些用于 Object
类的构造函数)在 constructor-body 之前都隐式地包含另一个实例构造函数的调用.隐式调用的构造函数由 constructor-initializer 决定:
All instance constructors (except those for class
Object
) implicitly include an invocation of another instance constructor immediately before the constructor-body. The constructor to implicitly invoke is determined by the constructor-initializer:
所以这个语法的官方技术术语...
So the offiical technical term for this syntax...
: base(x, y, z)
... 是构造函数初始化器",但是规范并没有专门调用冒号语法并给它自己的名字.作者假设规范不关心这些琐碎的事情.
...is "constructor-initializer", however the specification does not specifically call out the colon syntax and give it its own name. This author assumes the specification does not concern itself with such trivialities.
这篇关于构造函数定义中的这个冒号是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!