结构 - Layout.Explicit - 构造函数 - 完全分配字段 [英] Struct - Layout.Explicit - Constructor - fully assign fields

查看:27
本文介绍了结构 - Layout.Explicit - 构造函数 - 完全分配字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么如果我使用:

struct MyStruct
{
        [FieldOffset (0)] public uint Data;
        [FieldOffset (0)] public byte Something;
}

public MyStruct (uint pData)
{
   Data = pData; // setting Data field also sets Something field
}

C# 说我需要分配Something"字段:/我知道我可以做一个构造函数:这个()"但是编译器应该知道'Data'字段包含'Something'字段.

C# says i need to assign 'Something' field :/ I know I can do a "Constructor : this ()" but compiler should know 'Data' field contains 'Something' field.

所以,我应该先调用无参数构造函数,这是唯一的方法吗?

So, I should call parameterless constructor first, is it the only way?

推荐答案

是的,您需要调用默认构造函数.

Yes, you'll need to call the default constructor.

public MyStruct (uint pData) : this()
{
   //...
}

然后编译器将在构造函数的开头生成以下 IL 指令:

The compiler will then generate the following IL instructions at the beginning of your constructor:

ldarg.0           // Push address of struct onto stack
initobj MyStruct  // Pop address of struct and initialize it with "all zeros"

这篇关于结构 - Layout.Explicit - 构造函数 - 完全分配字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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