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

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

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

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-07 20:08

    If you mean if you can do ctor chaining in C#, the answer is yes. The question has already been asked.

    However it seems from the comments, it seems what you really intend to ask is 'Can I call an overloaded constructor from within another constructor with pre/post processing?'
    Although C# doesn't have the syntax to do this, you could do this with a common initialization function (like you would do in C++ which doesn't support ctor chaining)

    class A
    {
      //ctor chaining
      public A() : this(0)
      {  
          Console.WriteLine("default ctor"); 
      }
    
      public A(int i)
      {  
          Init(i); 
      }
    
      // what you want
      public A(string s)
      {  
          Console.WriteLine("string ctor overload" );
          Console.WriteLine("pre-processing" );
          Init(Int32.Parse(s));
          Console.WriteLine("post-processing" );
      }
    
       private void Init(int i)
       {
          Console.WriteLine("int ctor {0}", i);
       }
    }
    

提交回复
热议问题