C#隐式/显式字节数组转换

努斯蒂

我有以下问题。我想将整数值或浮点值转换为字节数组。通常,我使用BitConverter.GetBytes()方法。

int i = 10;
float a = 34.5F;
byte[] arr;

arr = BitConverter.GetBytes(i);
arr = BitConverter.GetBytes(a);

是否有可能使用隐式/显式方法执行此操作?

arr = i;
arr = a;

以及另一种方式?

i = arr;
a = arr;
丹·比斯特罗姆(DanByström)

您可以通过中级课程来实现。编译器本身不会执行两个隐式强制转换,因此您必须执行一个显式强制转换,然后编译器将找出第二个隐式强制转换。

问题是,与隐式类型转换,则必须投声明中投的类型,你无法从密封类像“诠释”继承。

因此,它一点也不优雅。扩展方法可能更优雅。

如果在下面声明该类,则可以执行以下操作:

        byte[] y = (Qwerty)3;
        int x = (Qwerty) y;

public class Qwerty
{
    private int _x;

    public static implicit operator byte[](Qwerty rhs)
    {
        return BitConverter.GetBytes(rhs._x);
    }

    public static implicit operator int(Qwerty rhs)
    {
        return rhs._x;
    }

    public static implicit operator Qwerty(byte[] rhs)
    {
        return new Qwerty {_x = BitConverter.ToInt32(rhs, 0)};
    }

    public static implicit operator Qwerty(int rhs)
    {
        return new Qwerty {_x = rhs};
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章