简体   繁体   中英

function() : this(null) {}

Can someone please explain the following syntactic sugar?

protected MyConstructor() : this(null)

Mainly I am interested in this part: " : this(null) "

I know how protected, constructors and "this" keyword work, but am confused and cannot find any detailed information of the last part all put-together in all my online searches.

Edit: I should add that it is in a public abstract class. So I guess the constructor is calling the implementers constructor.

Thanks

This is a special syntax for constructors. You can have two basic variants:

protected MyConstructor() : this(null)

Calls the different overload of the constructor with the null parameter.

protected MyConstructor() : base(null)

Calls the constructor on a base class with the null parameter.

So, you can have a class like this:

class MyClass
{
  object someObject;

  public MyClass() : this(null) {}
  public MyClass(object someObject) { this.someObject = someObject; }
}

Now you can instantiate the class like this:

var c = new MyClass(); // c.someObject is null
var c2 = new MyClass(new object()); // c2.someObject is some new object instance

This is required because you can't reuse constructor code in any other way. If you were just overriding or overloading a method, the equivalent would look like this:

public void DoStuff()
{
  DoStuff(null);
}

public void DoStuff(object someObject)
{
  // Do some stuff
}

It calls another class constructor that has a parameter:

protected MyConstructor() : this(null) { }  // This calls the other constructor

protected MyConstructor(object whatever)
{
    Frob(whatever);
}

There is another constructor on that same object, which takes some sort of nullable object. For example:

public MyConstructor(string str)
{
   // A
}


public MyConstructor() : this(null)
{
   // B
}

In this example (changing constructors to public for demonstration purposes), if I call:

var newObj = new MyConstructor();

It will create a MyConstructor object, run the code in A first (passing in null as the parameter) then run the code in B next.

This is a way of allowing you to consolidate common code that needs to run regardless of what constructor is called.

What this(null) is doing is calling another constructor in the same class that takes one parameter, and passing a null value as that parameter. Look into constructor overloading for more info. Also, constructor chaining is more pertinent to your question, but I'd look into both topics.

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