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

标签 c# structure unsafe

我在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/

相关文章:

c# - 结构布局优化

c - 使用 C 中的结构从文件读取数据时出现错误

c# - 在 C# 中使不安全代码变得安全

rust - 什么时候延长 Arenas 引用的生命周期是安全的?

c# - 如何在 .NET ConcurrentDictionary 中实现 remove_if 功能

c# - Html 敏捷包 Xpath

c++ - 如何在 C++ 中修复 "error: expected primary -expression before ' )' token"?

javascript - 如何从 javascript 文件中的 web.config 读取键值?

c# - 带等待的命名互斥量

rust - 使用 Transmute 的递归数据结构的零成本构建器模式。这安全吗?有更好的方法吗?