咨询C#中Constructor() : 后关键字的名称、类别及用途
Understanding Constructor Initializers in C#
Great question—these syntax bits you're seeing (: base() and : this()) are called constructor initializers in C#. They let you chain constructors together, either in the same class or with a parent class, to avoid redundant code and ensure proper initialization. Let's break down each one clearly:
1. base(): Calling a Base Class Constructor
- What it does: When you inherit from a base class,
base()tells your derived class constructor to first run a constructor from the parent (base) class. This ensures the base class's fields and initialization logic are set up before the derived class does its own work. - Example:
When you create apublic class Animal { protected string Species; // Base class constructor with a parameter public Animal(string species) { Species = species; Console.WriteLine($"Animal initialized as {Species}"); } } public class Dog : Animal { public Dog() : base("Canine") // Calls Animal(string) constructor first { Console.WriteLine("Dog initialized"); } }Doginstance, it first runsAnimal("Canine")to set the species, then executes theDogconstructor's logic. - Key detail: If you don't explicitly write
base(), C# will automatically try to call the base class’s parameterless constructor by default. But if the base class only has constructors with parameters, you must explicitly usebase(arguments)to match one of its constructors—otherwise, you’ll get a compile error.
2. this(): Calling Another Constructor in the Same Class
- What it does:
this()lets you reuse code between overloaded constructors in the same class. Instead of writing the same initialization logic multiple times, you can have one "primary" constructor with all the core logic, and other constructors call it usingthis(). - Example:
When you callpublic class Person { public string Name { get; set; } public int Age { get; set; } // Primary constructor with all parameters public Person(string name, int age) { Name = name; Age = age; Console.WriteLine($"Person {Name}, {Age} initialized"); } // Overloaded constructor that reuses the primary one public Person(string name) : this(name, 0) // Calls Person(string, int) with age=0 { // No need to repeat Name assignment here—it’s handled in the primary constructor } }new Person("Alice"), it triggersPerson("Alice", 0)under the hood, reusing the shared initialization code. - Key detail: You can chain multiple constructors this way, but you can’t create a circular chain (e.g., Constructor A calls Constructor B, which calls Constructor A)—that will cause a compile error.
Quick Recap
- Constructor initializers are the
: base()/: this()syntax after a constructor declaration. - Use
base()to initialize the base class before the derived class runs its logic. - Use
this()to reuse constructor logic within the same class, cutting down on code duplication.
内容的提问来源于stack exchange,提问作者Mohamed Benkedadra
相关产品推荐
相关产品推荐

