C#构造函数-为什么仅当没有构造函数时才由编译器生成默认构造函数,而不是在没有默认构造函数时才生成默认构造函数 [英] C# Constructor - why default constructor is generated by compiler only if there is no constructor, instead of when there is no default constructor

查看:86
本文介绍了C#构造函数-为什么仅当没有构造函数时才由编译器生成默认构造函数,而不是在没有默认构造函数时才生成默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据MSDN的构造函数设计指南


如果您没有在类型上显式声明任何构造函数,则许多语言(例如(如C#)会自动添加一个公共的默认构造函数。(抽象类将获得受保护的构造函数。)
向类中添加参数化的构造函数会阻止编译器添加默认构造函数。意外更改。

"If you don’t explicitly declare any constructors on a type, many languages (such as C#) will automatically add a public default constructor. (Abstract classes get a protected constructor.) Adding a parameterized constructor to a class prevents the compiler from adding the default constructor. This often causes accidental breaking changes."

为什么不这么做:


如果您没有在类型上明确声明任何 default 构造函数,则许多语言(例如C#)将自动添加公共的默认构造函数。(抽象类获得受保护的构造方法。)

"If you don’t explicitly declare any default constructors on a type, many languages (such as C#) will automatically add a public default constructor. (Abstract classes get a protected constructor.)"

这是什么原因?

推荐答案

因为并非所有的类 都应构造为无参数的。

Because not all classes should be constructed parameterless.

请考虑一个旨在实现两者之间接口的类。您的应用程序和磁盘上的文件。不得不处理构造对象而不指定要管理哪个文件的情况。

Consider a class that is designed to implement the interface between your application and a file on disk. It would be very inconvenient having to handle the case where the object is constructed without specifying which file to manage.

因此,由于创建非静态对象的要点class是您要创建其对象的对象,因此无需添加空的无参数构造函数(如果您只想拥有)。

As such, since the main point of creating a non-static class is that you want to create objects of it, you're spared having to add an empty parameterless constructor if that is all you want to have.

一旦您开始完全添加构造函数 ,则自动魔术功能将被禁用,并且将不提供默认构造函数。

Once you start adding constructors at all, then the automagic is disabled and no default constructor will be provided.

这篇关于C#构造函数-为什么仅当没有构造函数时才由编译器生成默认构造函数,而不是在没有默认构造函数时才生成默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆