开发者

C# inheritance and the "this" keyword

I am working on some code that was previously written by another developer, and I came across the block of code below:

/// <su开发者_如何学运维mmary>
/// Default Constructor.
/// </summary>
public Body(Revision parent)
{
  mContainer = parent;
  mSections = new ArrayList();
  mSummary = new ArrayList();
}

/// <summary>
/// Constructs a Body from specified ParseElement.
/// </summary>
/// <param name="parent">Revision container.</param>
/// <param name="elem">Source ParseElement.</param>
public Body(Revision parent, ParseElement elem) : this(parent)
{more constructing stuff}

From what I understand, is that the overloaded constructor would also call the default constructor with the Revision that I send in, causing the initialized ArrayLists to be accessible from the overloaded constructor. Is this correct, or am I totally confused?


Yes, that is correct. However, to correct your terminology:

  • There is no "default constructor" except possibly the parameterless constructor, which doesn't appear to exist on this class.
  • This has nothing whatsoever to do with inheritance. This technique is actually called constructor chaining.


This is correct and the technique is called constructor chaining. In this scenario the this call can be loosely visualized as saying

Run the specified constructor before the current constructor

They both run against the same object instance so changes in the called on are visible in the original.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜