: this(foo) syntax in C# constructors?

后端 未结 7 1942
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 19:53

Every now and then, I bump into syntax that I\'ve seen before, but never used. This is one of those times.

Can someone explain the purpose of \":this\" or \":base\"

7条回答
  •  鱼传尺愫
    2020-12-14 19:57

    It's like this if i'm not mistaken:

    public MyClass(SomeArg arg) : this(new SomethingElse(), arg)
    

    will call

    public MyClass(SomethingElse arg, SomeArg arg1) : base or this or nothing
    

    and that will go on until you got a base or nothing.

    If you have base(....) then that constructor having that will call the base constructor with the parameters (if any) given, which in turn can delegate to its own constructors (same game).

    If you have nothing, then the parameter-less constructor of the base-class is called automatically.

    After you have used this(....), then the constructor matching the parameters will be used and its body will be executed - additionally to the body of the constructor having used this(....).

提交回复
热议问题