简体   繁体   中英

What does this colon (:) mean?

Before the this keyword is a colon. Can anyone explain what the colon means in this context? I don't believe this is inhertance.

Thanks

using System;

namespace LinkedListLibrary
{
    class ListNode
    {
        private object data;
        private ListNode next;

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

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

        public ListNode Next
        {
            get
            {
                return next;
            }
            set
            {
                next = value;
            }
        }
        public object Data
        {
            get
            {
                return data;
            }
        }


    }
}

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.

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.

这意味着在运行主体之前,请运行带有object和ListNode参数的构造函数。

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM