What is this colon in a constructor definition cal

2019-08-07 04:00发布

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条回答
【Aperson】
2楼-- · 2019-08-07 04:42

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.

查看更多
登录 后发表回答