Skip to main content
 首页 » 编程设计

c#之构造函数定义中的这个冒号叫什么

2024年02月06日17cyq1162

在 C# 中定义构造函数时,可以使用冒号(如 this example ):

 public class Custom : OtherClass { 
      public Custom(string s) : base(s) { } 
 } 

这个冒号叫什么? (如果不知道它叫什么,很难读懂它。)

请注意,我问的是 constructor 定义中的冒号,而不是类定义中显示继承的冒号。

请您参考如下方法:

那不是方法定义,而是构造函数定义;冒号用于指定必须在子类的构造函数之前调用的父类(super class)构造函数调用。

在 Java 中,使用了 super 关键字,但它必须是子类构造函数中的第一个操作,而 C# 使用的语法更接近于 C++ 的初始化列表。

如果子类的“父类(super class)”构造函数没有任何参数,则不需要显式调用父类构造函数,只有在需要参数时或者如果要调用特定的重载构造函数才必须使用此语法。

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 节“构造函数初始化器”中有解释

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)  

...是“构造函数初始化器”,但是规范没有特别指出冒号语法并给它自己的名字。这位作者假设规范本身不关心这些琐碎的事情。