C#中构造函数

本文详细解释了构造函数的作用及其在C#中的工作原理,包括实例构造函数如何初始化对象、静态构造函数如何初始化类等内容。

1。长久以来的概念一直是构造函数用来生成一个对象的实例,因为生成对象时需要使用构造函数。如

Class1 obj = new Class1(). 因为使用了new 关键字,所以往往认为是构造函数创建了对象。

其实不是,构造函数只是一个函数,是用来初始化对象用的,而不是用来创建对象用的,即对象内存的分配等不是由构造函数完成的,只是在创建对象的时候,总是会调用构造函数来完成一些初始化的工作。

2。Broadly speaking, a constructor is a method in the class which gets executed when its object is created.When the object of this class is instantiated, this constructor will be executed.

构造函数是一个在对象生成时被调用的函数

3。An instance constructor is a member that implements the actions required to initialize an instance of a class

Instance constructors are invoked by object-creation-expressions and through constructor-initializers.

4。Understanding the way constructors work in C# required one of the biggest mental leaps for me in coming from C++. Almost every detail of how constructors work is different between the two languages. The most glaring difference is how the type of the object varies (or doesn't vary) during construction. In C++, the vptr of the object mutates as it is constructed from the base class to the derived class, so calling virtual functions in a constructor body won't give you implementations from more-derived types. In contrast, the C# and CLR set the vptr once to the most derived type, which means virtual types are dispatched to the most derived type even when called from a base type's constructor. If those virtual types rely on the derived type's constructor body running, then watch out!

All instance constructors (except those for class object) implicitly include an invocation of another instance constructor immediately before the constructor-body

5。Variable initializers are transformed into assignment statements, and these assignment statements are executed before the invocation of the base class instance constructor. This ordering ensures that all instance fields are initialized by their variable initializers before any statements that have access to that instance are executed.

变量初始化在所有构造函数执行之前进行,这点同java不一样

6。A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced

静态构造函数用来实现那些仅执行一词的动作或者实例化静态数据。实例构造函数来初始化一个对象,静态构造函数来初始化一个类

  • A static constructor does not take access modifiers or have parameters.

  • A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

  • A static constructor cannot be called directly.

  • The user has no control on when the static constructor is executed in the program.

  • A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

  • Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

  • If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

As with instance initializers, the static initializers are called before any static constructors are called. And, yes, your static initializers execute before the base class's static constructor.
和实例初始化器一样,静态初始化器在任何静态构造函数被调用之前被调用。同时,静态初始化器在基类的静态构造函数之前被执行。当你的类型首次被加载到应用程序空间时,

The CLR calls your static constructor automatically when your type is first loaded into an application space. You can define only one static constructor, and it must not take any arguments. Because static constructors are called by the CLR, you must be careful about exceptions generated in them. If you let an exception escape a static constructor, the CLR will terminate your program. Exceptions are the most common reason to use the static constructor instead of static initializers. If you use static initializers, you cannot catch the exceptions yourself. With a static constructor, you can.
CLR 自动调用静态构造函数。你可以仅仅定义一个静态构造函数,它必须不带任何参数。因为静态构造函数是由CLR调用的,你必须当心在它们中出现的异常。如果让 异常跳出静态构造函数,CLR将会终止你的程序。使用静态构造函数而不是静态初始化器的最常见的原因就是异常处理。如果使用静态初始化器,就不可能自己捕 获异常了。有了静态构造函数,才可以

C#中构造函数同Java中构造函数的区别

 

http://www.wewill.cn/n19918c53.aspx

### C#构造函数调用基类构造方法的方式 在 C# 中,当定义一个派生类时,默认情况下会尝试调用其基类的无参构造函数。如果基类存在有参数的构造函数而未提供无参构造函数,则需要显式指定如何调用这些构造函数。这可以通过 `base` 关键字来完成。 #### 基本概念 - 如果派生类的构造函数没有显式的构造函数初始化语句(即没有使用 `base` 或者 `this`),则编译器会在内部自动生成一条对基类无参构造函数的调用[^1]。 - 若基类不存在无参构造函数或者需要传递特定参数给基类构造函数,则必须通过 `base` 显式调用来实现这一点[^2]。 以下是几种常见的场景及其对应的代码示例: --- #### 场景一:无参构造函数的继承与调用 在这种情况下,派生类无需任何额外操作即可自动调用基类中的无参构造函数。 ```csharp class Animal { public Animal() { Console.WriteLine("我是动物基类(父类)"); } } class Dog : Animal { public Dog() { Console.WriteLine("我是小狗(子类)"); } } ``` 运行上述代码的结果将是先打印 `"我是动物基类(父类)"`,随后打印 `"我是小狗(子类)"`[^3]。 --- #### 场景二:显式调用基类的无参构造函数 即使可以省略 `base()` 的写法,为了提高可读性和一致性,也可以手动写出该部分逻辑。 ```csharp class DrivedClass : BaseClass { public DrivedClass() : base() { // 显示调用了基类的无参构造函数 ... } } ``` 这种方式特别适用于团队协作环境下的代码维护工作,因为明确指出了依赖关系。 --- #### 场景三:带有参数的基类构造函数 当基类提供了含参数的构造函数而非简单的无参版本时,派生类需利用 `base` 提供必要的实参列表以匹配目标签名。 假设有一个接受字符串作为输入的基类构造函数: ```csharp class Person { private string name; public Person(string n) { this.name = n; Console.WriteLine($"Person created with name: {n}"); } } class Employee : Person { public Employee(int id, string empName) : base(empName) { // 将empName传入到基类构造函数中 int employeeId = id; Console.WriteLine($"Employee ID is set to {employeeId}"); } } ``` 在此案例中,每当创建一个新的 `Employee` 对象时,不仅设置了员工编号 (`id`) 还向基类传递了名字(`empName`) 以便执行相应的初始化过程[^4]。 --- #### 总结说明 综上所述,在 C# 编程语言环境下,无论是简单还是复杂的继承结构下都可以灵活运用 `base` 实现定制化的实例化行为;同时注意遵循良好的编码实践原则比如始终考虑兼容性问题并保持清晰易懂的源码风格。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值