Can I call an overloaded constructor from another constructor of the same class in C#?

前端 未结 4 2030
走了就别回头了
走了就别回头了 2020-12-07 19:31

Can I call an overloaded constructor from another constructor of the same class in C#?

4条回答
  •  星月不相逢
    2020-12-07 19:57

    EDIT: According to the comments on the original post this is a C# question.

    Short answer: yes, using the this keyword.

    Long answer: yes, using the this keyword, and here's an example.

    class MyClass
    {
       private object someData;
    
       public MyClass(object data)
       {
          this.someData = data;
       }
    
       public MyClass() : this(new object())
       {
          // Calls the previous constructor with a new object, 
          // setting someData to that object
       }
    }
    

提交回复
热议问题