What is this colon in a constructor definition called?

99封情书 提交于 2019-12-13 19:47:16

问题


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) { }
 }

What is this colon called? (It's awfully hard to read about it without knowing what it's called.)

Note that I'm asking about the colon in the constructor definition, not the one showing inheritance in the class definition.


回答1:


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.

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) {
    }
}

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"

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.



来源:https://stackoverflow.com/questions/29423148/what-is-this-colon-in-a-constructor-definition-called

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!