.Net C#语法 构造函数中this和base

类:

    public class TestClassA
    {
        public TestClassA()
        {
            Console.WriteLine("我是在TestClassA中的TestClassA()构造函数中");
        }
        public TestClassA(string a, string b)
        {
            Console.WriteLine("我是在TestClassA中的TestClassA(string a, string b)构造函数中");
        }
        public TestClassA(string a)
            : this(a, "b")
        {
            Console.WriteLine("我是在TestClassA中的TestClassA(string a): this(a, \"b\")构造函数中");
        }
    }

    public class TestClassB : TestClassA
    {
        public TestClassB()
        {
            Console.WriteLine("我是在TestClassB中的TestClassB()构造函数中");
        }
        public TestClassB(string a, string b)
            : base(a, b)
        {
            Console.WriteLine("我是在TestClassB中的TestClassB(string a, string b): base(a, b)构造函数中");
        }

        public TestClassB(string a)
            : this(a, "b")
        {
            Console.WriteLine("我是在TestClassB中的TestClassB(string a, string b): this(a, \"b\")构造函数中");
        }
    }

实例:

        Console.WriteLine("TestClassA Father1 = new TestClassA();运行结果:"); 
        TestClassA Father1 = new TestClassA(); 
        Console.WriteLine(); 
        Console.WriteLine("TestClassA Father2 = new TestClassA(\"f2\", \"f2\");运行结果:"); 
        TestClassA Father2 = new TestClassA("f2", "f2"); 
        Console.WriteLine(); 
        Console.WriteLine("TestClassA Father3 = new TestClassA(\"f3\");运行结果:"); 
        TestClassA Father3 = new TestClassA("f3"); 
        Console.WriteLine();
        Console.WriteLine("TestClassB Son1 = new TestClassB();运行结果:");
        TestClassB Son1 = new TestClassB();             
        Console.WriteLine();
        Console.WriteLine("TestClassB Son2 = new TestClassB(\"s2\", \"s2\");运行结果:");
        TestClassB Son2 = new TestClassB("s2", "s2");
        Console.WriteLine();             
        Console.WriteLine("TestClassB Son3 = new TestClassB(\"s3\");运行结果:");
        TestClassB Son3 = new TestClassB("s3");
        Console.WriteLine();

结果:

分析:

this:调用的是本身,不能调用父类和子类的

base:调用父类的,不能调用本身的,但别人继承,可以调用

从中也可以得出另外个结果构造函数的运行过程 先从基类开始构造再到类本身

 

本博客内容有些来源于网络或书籍如果侵害到你的权益,请及时联系我(hch458458@vip.qq.com)
版权归nethch所有,转载请注明出处!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值