Call one constructor from the body of another in C#

前端 未结 6 1771
情深已故
情深已故 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:55

    To call both base and this class constructor explicitly you need to use syntax given below (note, that in C# you can not use it to initialize fields like in C++):

    class foo
    {
        public foo (int x, int y)
        {
        }
    
        public foo (string s) : this(5, 6)
        {
            // ... do something
        }
    }
    

    //EDIT: Noticed, that you've used x,y in your sample. Of course, values given when invoking ctor such way can't rely on parameters of other constructor, they must be resolved other way (they do not need to be constants though as in edited code sample above). If x and y is computed from s, you can do it this way:

    public foo (string s) : this(GetX(s), GetY(s))
    

提交回复
热议问题