问题
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;
}
}
}
}
回答1:
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.
回答2:
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.
回答3:
It means before running the body, run the constructor with object and ListNode parameters.
回答4:
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.
回答5:
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.
回答6:
Constructor chain arguments. There is also ": base()" for chaining a call to a constructor on the base type.
回答7:
The code is telling the other constructor to execute with the supplied arguments before the body of the current constructor is executed.
来源:https://stackoverflow.com/questions/1071148/what-does-this-colon-mean