构造函数定义中的这个冒号叫什么?
What is this colon in a constructor definition called?
在 C# 中定义构造函数时,可以使用冒号(如 this example):
public class Custom : OtherClass {
public Custom(string s) : base(s) { }
}
这个冒号叫什么?(如果不知道它叫什么,很难阅读它。)
请注意,我问的是 constructor 定义中的冒号,而不是 class 定义中显示继承的冒号。
那不是方法定义,而是构造函数定义;冒号用于指定必须在子类的构造函数之前调用的超类构造函数调用。
在 Java 中,使用了 super
关键字,但它必须是子类构造函数中的第一个操作,而 C# 使用的语法更接近于 C++ 的初始化列表。
如果子类的“超类”构造函数没有任何参数,则不需要显式调用父构造函数,只有在需要参数时或者如果要调用特定的重载构造函数,才必须使用此方法语法。
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 节中有解释 "Constructor initializers"
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:
所以这个语法的官方技术术语...
: base(x, y, z)
... 是 "constructor-initializer",但是规范没有特别指出冒号语法并给它自己的名字。作者假设规范不关心这些琐碎的事情。
在 C# 中定义构造函数时,可以使用冒号(如 this example):
public class Custom : OtherClass {
public Custom(string s) : base(s) { }
}
这个冒号叫什么?(如果不知道它叫什么,很难阅读它。)
请注意,我问的是 constructor 定义中的冒号,而不是 class 定义中显示继承的冒号。
那不是方法定义,而是构造函数定义;冒号用于指定必须在子类的构造函数之前调用的超类构造函数调用。
在 Java 中,使用了 super
关键字,但它必须是子类构造函数中的第一个操作,而 C# 使用的语法更接近于 C++ 的初始化列表。
如果子类的“超类”构造函数没有任何参数,则不需要显式调用父构造函数,只有在需要参数时或者如果要调用特定的重载构造函数,才必须使用此方法语法。
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 节中有解释 "Constructor initializers"
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:
所以这个语法的官方技术术语...
: base(x, y, z)
... 是 "constructor-initializer",但是规范没有特别指出冒号语法并给它自己的名字。作者假设规范不关心这些琐碎的事情。