我已经在 c# 中实现了 c++ 联合,只是为了验证我理解它。但似乎我什么都不懂。我有时会期待完全不同的输出。我的代码:
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication2
{
[StructLayout(LayoutKind.Explicit)]
class union
{
[FieldOffset(0)]
public double d;
[FieldOffset(0)]
public float f0;
[FieldOffset(4)]
public float f1;
[FieldOffset(0)]
public int i0;
[FieldOffset(4)]
public int i1;
[FieldOffset(0)]
public short s0;
[FieldOffset(2)]
public short s1;
[FieldOffset(4)]
public short s2;
[FieldOffset(6)]
public short s3;
}
class Program
{
static void Main(string[] args)
{
union su = new union();
su.f0 = 19.012012F;
su.f1 = 3.14159265F;
Console.WriteLine(su.d);
Console.WriteLine(su.i0);
Console.WriteLine(su.i1);
Console.WriteLine(su.s0);
Console.WriteLine(su.s1);
Console.WriteLine(su.s2);
Console.WriteLine(su.s3);
Console.ReadLine();
}
}
}
我的输出是:
- 50,1238786690385
- 1100486810
- 1078530011
- 6298
- 16792
- 4059
- 16457
例如,我认为 s0 是 30209 而不是 6298。有人能解释一下它是如何工作的吗?