我在c#中有一个结构定义,如下所示
public struct test
{
byte SetCommonPOP;
byte SetCommonSVP;
byte SetCommonUHDP;
byte SetCommonMHDP;
};
如何将int y分配给此结构的对象x而不必使用unsafe?
答案 0 :(得分: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
部分 - 如果您使用的是uint
而不是int
,我也不会为此烦恼。提取有符号整数的部分只会让我感到抽搐,这可能是过度补偿。另一种选择是将value
转换为uint
作为开始的局部变量。
答案 1 :(得分: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;
}
}