为什么必须使用非默认构造函数初始化 C# 结构中的所有字段? [英] Why Must I Initialize All Fields in my C# struct with a Non-Default Constructor?

查看:11
本文介绍了为什么必须使用非默认构造函数初始化 C# 结构中的所有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想试试这个代码:

public struct Direction
{
   private int _azimuth;

   public int Azimuth
   {
     get { return _azimuth; }
     set { _azimuth = value; }
   }       

   public Direction(int azimuth)
   { 
      Azimuth = azimuth
   } 
}

但是它在编译时失败了,我知道 struct 需要初始化它的所有字段.但我试图了解 CLRIL 引擎盖下会发生什么.为什么它在任何其他方法属性这个等之前需要所有字段

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 CLRIL hoods. why it need all the fields before any other methodproperty his 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.

结构的默认构造函数(它不接受任何参数并且您不能明确指定)将结构的所有字段清零,因此您可以在完成后使用结构.

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 以安全/验证方式传递您的代码所必需的.

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 .

另见:CLR via C# 2nd Ed - Pg 188

See Also: CLR via C# 2nd Ed - Pg 188

这篇关于为什么必须使用非默认构造函数初始化 C# 结构中的所有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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