我为什么必须初始化所有字段在我的C#结构与非默认构造函数? [英] Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?
问题描述
我想试试这个code:
I would like to try this code:
public struct Direction
{
private int _azimuth;
public int Azimuth
{
get { return _azimuth; }
set { _azimuth = value; }
}
public Direction(int azimuth)
{
Azimuth = azimuth
}
}
但它编译失败,我明白该结构需要初始化所有的字段。
但我想了解的CLR \\ IL罩下会发生什么。
为什么它需要所有的字段之前的任何其他方法\\属性\\本等。
But it fails on compilation, I understand that struct need to init all its fields. but i am trying to understand what happens under the CLR\IL hoods. why it need all the fields before any other method\property\this etc.
感谢。
推荐答案
值类型堆栈(除非嵌套引用类型内),也有一些是关于栈的CLR不能保证在田/位置上创建他们将被清零(与场/这是保证托管堆上地点被清零)。因此,他们必须写入之前被读取。否则,它是一个安全漏洞。
Value Types are created on the stack (unless nested within a reference type) There is something about fields/locations on the stack that the CLR can't guarantee that they will be zeroed out (contrary to fields/locations on the managed heap which are guaranteed to be zeroed out). Hence they must be written to before being read. Otherwise it's a security hole.
该结构的默认构造函数(没有参数和你不能明确指定)置零一个struct的各个领域,因此这样做后,您可以使用一个结构。
The struct's default ctor (which takes no parameters and which you're not allowed to explicitly specify) zeroes out all fields of a struct and hence you can use a struct after you do.
new BimonthlyPairStruct()
然而,当你实现你的参数构造函数,您必须确保所有的字段都被初始化 - 这是必需的CLR通过您的code作为安全/ 验证
However when you implement your parameterized ctor, you must ensure that all fields have been initialized - which is required for the CLR to pass your code as safe/verified .
另请参见:通过C#第二版CLR - 皮克188
See Also: CLR via C# 2nd Ed - Pg 188
这篇关于我为什么必须初始化所有字段在我的C#结构与非默认构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!