c# :this() 和 :base()区别

在 C# 中,:this() 和 :base() 都用于构造函数的重载和继承,但它们有不同的用途和上下文:

1. :this()

  • 用途:用于调用当前类中的其他构造函数(构造函数重载)。

  • 场景:当你希望一个构造函数先执行另一个构造函数中的逻辑时使用。

  • 示例 :

    csharp 复制代码
    public class MyClass
    {
        public MyClass() : this("default") // 调用下面的构造函数
        {
            Console.WriteLine("无参构造函数");
        }
    
        public MyClass(string name)
        {
            Console.WriteLine($"带参构造函数,name: {name}");
        }
    }

    输出 (当调用 new MyClass() 时):

    复制代码
    带参构造函数,name: default
    无参构造函数

2. :base()

  • 用途:用于调用基类(父类)的构造函数。

  • 场景:在继承关系中,子类构造函数需要初始化基类的成员时使用。

  • 示例 :

    csharp 复制代码
    public class BaseClass
    {
        public BaseClass()
        {
            Console.WriteLine("基类构造函数");
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public DerivedClass() : base() // 显式调用基类构造函数(可省略)
        {
            Console.WriteLine("子类构造函数");
        }
    }

    输出 (当调用 new DerivedClass() 时):

    复制代码
    基类构造函数
    子类构造函数

关键区别

特性 :this() :base()
调用目标 当前类的其他构造函数 基类的构造函数
使用场景 构造函数重载(简化代码) 继承(初始化基类成员)
是否可选 可选(根据需要) 可选(如果基类有无参构造函数,可省略)

其他注意事项

  1. 如果省略 :base(),编译器会自动调用基类的无参构造函数(如果基类没有无参构造函数,则必须显式调用)。
  2. :this() 和 :base() 必须出现在构造函数声明之后,且只能选择其中之一(不能同时使用)。
  3. 它们可以带参数,例如 :this("hello") 或 :base(42)。
示例(结合使用)
csharp 复制代码
public class Animal
{
    public Animal(string name)
    {
        Console.WriteLine($"Animal: {name}");
    }
}

public class Dog : Animal
{
    public Dog() : this("Buddy") // 调用当前类的其他构造函数
    {
        Console.WriteLine("Dog()");
    }

    public Dog(string name) : base(name) // 调用基类构造函数
    {
        Console.WriteLine($"Dog(name: {name})");
    }
}

输出 (当调用 new Dog() 时):

复制代码
Animal: Buddy
Dog(name: Buddy)
Dog()
相关推荐
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹3 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
kybs19913 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
孙启超3 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int3 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
CoderYanger3 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
伞伞悦读3 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json