为什么c#没有联盟?

Fan*_*c23 4 c#

我试图理解为什么C#没有工会的技术背景.我明白使用具有显式结构布局的属性机制可以解决问题,我更感兴趣的是为什么这比vanilla union构造更受欢迎.

wj3*_*j32 6

允许工会会破坏.NET的安全性,特别是在涉及托管对象时.

例如(对于32位系统):

union MyUnion
{
    string SomeString; // just a 4 byte pointer
    uint SomeInteger;
}

MyUnion u;

u.SomeInteger = 0x98765432;
// What's u.SomeString? What happens if I try to access it?
Run Code Online (Sandbox Code Playgroud)

C#允许你使用unsafe关键字和某些属性来自己射击,但从不涉及托管类型.您可能已经注意到FieldOffset不允许您将随机类型组合在一起.尝试使用上面的"联合".

这是我得到的:

无法从程序集"ConsoleApplication2,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null"加载类型"MyUnion",因为它包含偏移0处的对象字段,该字段未正确对齐或由非对象字段重叠.