Call one constructor from the body of another in C#

前端 未结 6 1775
情深已故
情深已故 2020-12-30 18:12

I need to call one constructor from the body of another one. How can I do that?

Basically

class foo {
    public foo (int x, int y)
    {
    }

             


        
6条回答
  •  悲&欢浪女
    2020-12-30 19:12

    I've ran into this problem a time or two myself... I ended up having to extract whatever logic I needed in that other constructor into a private void method and calling it in both places.

    class foo
    {
      private void Initialize(int x, int y)
      {
        //... do stuff
      }
    
      public foo(int x, int y)
      {
        Initialize(x, y);
      }
    
      public foo(string s_
      {
        // ... do stuff
    
        Initialize(x, y)
        // ... more stuff
      }
    }
    

提交回复
热议问题