C# 为什么结构不能有无参数构造函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/575901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why struct can not have parameterless constructor
提问by Praveen Sharma
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.
为什么结构不能有无参数构造函数?为 CLR 执行此操作有什么问题或为什么不允许这样做?请解释一下,因为我不明白。
采纳答案by Rauhotz
I cannot have an explicit parameterless constructor, only the implicit one, that initializes all members to their default.
我不能有一个显式的无参数构造函数,只有隐式的构造函数,它将所有成员初始化为默认值。
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, ...
尽管 CLR 允许,但 C# 不允许结构具有默认的无参数构造函数。原因是,对于值类型,默认情况下编译器既不生成默认构造函数,也不生成对默认构造函数的调用。所以,即使你碰巧定义了一个默认构造函数,它也不会被调用,这只会让你感到困惑。为避免此类问题,C# 编译器不允许用户定义默认构造函数。并且因为它不生成默认构造函数,所以在定义字段时不能初始化它们,...
回答by petr k.
Quite a reasonable explanation can be found at: http://en.csharp-online.net/CSharp_FAQ:_Why_must_struct_constructors_have_at_least_one_argument
可以在以下位置找到相当合理的解释:http: //en.csharp-online.net/CSharp_FAQ: _Why_must_struct_constructors_have_at_least_one_argument
Quoting: "The .NET Common Language Runtime (CLR) does not guarantee that parameterless constructors will be called. If structs were permitted to have default, parameterless constructors, the implication would be that default constructors would always be called. Yet, the CLR makes no such guarantee."
引用: “.NET 公共语言运行时 (CLR) 不保证会调用无参数构造函数。如果允许结构具有默认的无参数构造函数,则暗示将始终调用默认构造函数。然而,CLR 使没有这样的保证。”