Call one constructor from the body of another in C#

前端 未结 6 1772
情深已故
情深已故 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 18:53

    You can't.

    You'll have to find a way to chain the constructors, as in:

    public foo (int x, int y) { }
    public foo (string s) : this(XFromString(s), YFromString(s)) { ... }
    

    or move your construction code into a common setup method, like this:

    public foo (int x, int y) { Setup(x, y); }
    public foo (string s)
    {
       // do stuff
       int x = XFromString(s);
       int y = YFromString(s);
       Setup(x, y);
    }
    
    public void Setup(int x, int y) { ... }
    

提交回复
热议问题