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

前端 未结 4 2021
走了就别回头了
走了就别回头了 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
       }
    }
    
    0 讨论(0)
  • 2020-12-07 20:05

    In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().

    When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

    0 讨论(0)
  • 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);
       }
    }
    
    0 讨论(0)
  • 2020-12-07 20:11

    No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example

    class foo
    {
        public foo(){}
        public foo(string s ) { }
        public foo (string s1, string s2) : this(s1) {....}
    
    }
    
    0 讨论(0)
提交回复
热议问题