简体   繁体   中英

Can I call constructor from another constructor (as a regular method)?

Let's say I have 2 constructors.

public class MyClass
{
   public MyClass()
   {
     int id = 0;
     //Same behaviour
   }
   Public MyClass(int id)
   {
     //Same behaviour
   }
}

Both constructions implement the same behavior. The only difference is that, if the first constructor is called and the value of id = 0;

My question is to know if I can call the second constructor, instead of implemetanting the same behavior? If that's possible, do I do it?

You can do this:

public class MyClass {
    public MyClass() : this(0) {
    }
    public MyClass(int id) {
    }
}

Here's Microsoft's documentation on it. (you have to scroll down a bit; try searching for : this )

public class MyClass
{
   public MyClass() : this(0)
   {
   }
   public MyClass(int id)
   {
     //Same behaviour
   }
}

Yes, this is called constructor chaining. It's achieved like so:

public class MyClass {
    public MyClass() : this(0) { }
    public MyClass(int id) {
        this.id = id;
    }
}

Note that you can chain to the base-class constructor like so:

public class MyClass : MyBaseClass {
    public MyClass() : this(0) { }
    public MyClass(int id) : base(id) { }
}

public class MyBaseClass {
    public MyBaseClass(int id) {
        this.id = id;
    }
}

If there is a base class and you don't specify a constructor to chain to, the default is the accessible parameterless constructor, if there is one. If you do not specify a constructor to chain to and there is no accessible parameterless constructor, you will get a compile-time error.

If this is C# 4, an alternative is to use a default value for the constructor parameter (effectively making it optional ):

public MyClass(int id = 0) { ...

I think this is the ideal solution for your example.

But it depends on whether you'd like to use this class as a type argument for a type parameter with a constructor constraint...

为什么不将这个相同的行为放在私有函数中?

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