: this(foo) syntax in C# constructors?

后端 未结 7 1920
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 19:53

Every now and then, I bump into syntax that I\'ve seen before, but never used. This is one of those times.

Can someone explain the purpose of \":this\" or \":base\"

相关标签:
7条回答
  • 2020-12-14 20:22

    Your gut feeling is right. The syntax is used to call overloaded constructors in the same class:

    public class Test
    {
        public Test() : this("Called from default constructor") { }
        public Test(String msg)
        {
            Console.WriteLine(msg);
        }
    }
    

    The following code:

    public static void Main(String[] args)
    {
        Test t1 = new Test();
        Test t2 = new Test("Called from Main function");
    }
    

    Outputs the following

    Called from default constructor
    Called from main function

    Similarly, : base(someParams) is used to call base constructors.

    0 讨论(0)
提交回复
热议问题