What does this colon (:) mean?

你离开我真会死。 提交于 2019-11-27 19:18:22

It (along with the this keyword) is instructing the constructor to call another constructor within the same type before it, itself executes.

Therefore:

public ListNode(object dataValue)
    : this(dataValue, null)
{
}

effectively becomes:

public ListNode(object dataValue)
{
    data = dataValue;
    next = null;
}

Note that you can use base instead of this to instruct the constructor to call a constructor in the base class.

Quintin Robinson

It is constructor chaining so the constructor with the subsequent : this call will chain to the ctor that matches the signature.

So in this instance

public ListNode(object dataValue)

is calling

public ListNode(object dataValue, ListNode nextNode)

with null as the second param via : this(dataValue, null)

it's also worth noting that the ctor called via the colon executes before the ctor that was called to initialize the object.

It means before running the body, run the constructor with object and ListNode parameters.

It calls the other ListNode constructor. You can do a similar thing with the base keyword to call a constructor of a class you're deriving from.

No, that enables you to execute the existing constructor overload (the one with two parameters), before executing the body of the new constructor.

That's the simplest way to reuse the constructor code in multiple constructor overloads.

Constructor chain arguments. There is also ": base()" for chaining a call to a constructor on the base type.

The code is telling the other constructor to execute with the supplied arguments before the body of the current constructor is executed.

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