在不使用不安全的情况下将 int 分配给结构体对象

本文关键字:分配 int 结构体 对象 情况下 不安全 | 更新日期: 2023-09-27 18:36:27

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

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

如何将 int y 分配给此结构的对象 x 而不必使用 unsafe?

在不使用不安全的情况下将 int 分配给结构体对象

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

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部分 - 如果您使用的是uint而不是int,我不会打扰它们。提取有符号整数的一部分只会让我抽搐,这可能是过度补偿。另一种选择是将value转换为uint作为局部变量。

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

[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;
    }
}