문제

I have a struct definition in c# as follows

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

How do I assign an int y to an object x of this structure without having to use unsafe?

도움이 되었습니까?

해결책

You could write a custom conversion operator:

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

Personally I'd prefer a static FromInt32 method instead of an implicit operator, but that's your call. It's very possible that you don't need all the & 0xff parts in the conversion - and I wouldn't bother with them if you were using a uint instead of an int. Extracting parts of a signed integer just makes me twitchy, and this is possibly overcompensation. Another alternative would be a cast of value to a uint as a local variable to start with.

다른 팁

Another option is to use an explicit struct layout:

[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;
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top