我在c#中有一个结构定义如下
public struct test
{
byte SetCommonPOP;
byte SetCommonSVP;
byte SetCommonUHDP;
byte SetCommonMHDP;
};
如何在不使用 unsafe 的情况下将 int y 分配给此结构的对象 x?
最佳答案
您可以编写自定义转换运算符:
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
作为开始的局部变量。
关于c# - 在不使用不安全的情况下将 int 分配给结构对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19500073/