为什么结构不能有参数的构造函数 [英] Why struct can not have parameterless constructor

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

问题描述

为什么结构不能有参数的构造函数?
是什么在做这CLR的问题,或者它为什么不允许?
请解释一下,因为我不明白。

Why struct can not have parameterless constructor? What's the problem in doing this for CLR or why it's not allowed ? Please explain it as I don't understand it.

推荐答案

我不能有一个明确的参数的构造函数,只有隐含的一个,那所有成员初始化为它们的默认。

I cannot have an explicit parameterless constructor, only the implicit one, that initializes all members to their default.

虽然CLR允许,C#确实
不允许结构有默认
参数的构造函数。究其原因
是,对于值类型,默认情况下编译器
既不产生一个默认的
构造,也不会产生
调用默认的构造函数。所以,即使你碰巧定义
默认构造函数
,它不会被称为
和只会混淆你。
。要避免这样的问题,C#
编译器用户不允许一个
默认构造函数的定义。和
,因为它不会产生一个默认的
的构造函数,你不能定义它们,...

Although the CLR allows it, C# does not allow structs to have a default parameterless constructor. The reason is that, for a value type, compilers by default neither generate a default constructor, nor do they generate a call to the default constructor. So, even if you happened to define a default constructor, it will not be called and that will only confuse you. To avoid such problems, the C# compiler disallows definition of a default constructor by the user. And because it doesn't generate a default constructor, you can't initialize fields when defining them, ...

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

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