3

我在 c# 中有一个结构定义如下

public struct test                                                                                  
{
    byte   SetCommonPOP;
    byte   SetCommonSVP;
    byte   SetCommonUHDP;
    byte   SetCommonMHDP;
};

如何在不使用 unsafe 的情况下将 int y 分配给此结构的对象 x?

4

2 回答 2

8

您可以编写一个自定义转换运算符:

public struct Test
{
    private readonly byte pop;
    private readonly byte svp;
    private readonly byte uhdp;
    private readonly byte mhdp;

    // TODO: Properties to return the above

    public Test(byte pop, byte svp, byte uhdp, byte mhdp)
    {
        this.pop = pop;
        this.svp = svp;
        this.uhdp = uhdp;
        this.mhdp = mhdp;
    }

    public static implicit operator Test(int value)
    {
        // Working from most significant to least significant bits...
        byte mhdp = (byte) ((value >> 0) & 0xff);
        byte uhdp = (byte) ((value >> 8) & 0xff);
        byte svp = (byte) ((value >> 16) & 0xff);
        byte pop = (byte) ((value >> 24) & 0xff);
        return new Test(pop, svp, uhdp, mhdp);
    }
}

就个人而言,我更喜欢静态FromInt32方法而不是隐式运算符,但这是你的电话。您很可能不需要& 0xff转换中的所有部分 - 如果您使用的是 auint而不是int. 提取有符号整数的一部分只会让我抽搐,这可能是过度补偿。另一种选择是将 a 强制value转换uint为局部变量。

于 2013-10-21T16:45:15.227 回答
1

另一种选择是使用显式结构布局:

[StructLayout(LayoutKind.Explicit)]
public struct Test
{
    [FieldOffset(3)]
    public readonly byte pop;
    [FieldOffset(2)]
    public readonly byte svp;
    [FieldOffset(1)]
    public readonly byte uhdp;
    [FieldOffset(0)]
    public readonly byte mhdp;

    [FieldOffset(0)]
    private int value;

    public static Test FromInt32(int value)
    {
        var test = new Test();
        test.value = value;
        return test;
    }
}
于 2013-10-21T17:12:26.163 回答