为什么不总是有默认构造函数 [英] why is there not always a default constructor

查看:82
本文介绍了为什么不总是有默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,当我创建一个空类时,它提供了默认构造函数,但是当我为构造函数提供参数时,将不再创建默认构造函数。

In C# when I create an empty class it provides a default constructor however when I provide a constructor with parameters the default constructor is no longer created.

我的问题是:


  1. 为什么编译器不再给我默认构造函数也是如此?

  2. 是否有一个设置可以始终生成此默认构造函数?

这些问题出现了与WCF一起工作,我既需要默认构造函数,又希望能够为构造函数提供值,最好不要每次都放置默认构造函数,而且我认为未使用的默认构造函数不会带来很多收益

These questions arose from working with WCF where I require the default constructor but also want to be able to provide a constructor with values and it would be nice not to have to place the default constructor in every time and I wouldn't think unused default constructors would make much overhead.

推荐答案

(通常)具有自定义构造函数意味着该对象的内部状态会使用一些自定义信息进行初始化通过构造函数参数提供。如果在这种情况下仍具有默认构造函数,那么初始状态将是什么?

Having a custom constructor (usually) means that the internal state of the object is initialized with some custom information that you provide via constructor parameters. If you still had the default constructor in such a case, what would the initial state be?

如果您没有自定义构造函数,那么假设您只是自定义构造函数就可以了使用默认构造函数,因为没有内部状态可以初始化。

If you have no custom constructor then it is assumed to be fine if you just use the default constructor because there is no internal state to initialize.

这篇关于为什么不总是有默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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