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

时间:2015-01-23 09:10:09

标签: c# implicit-cast

我有以下问题。我想将整数值或浮点值转换为字节数组。 Normaly我使用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;

2 个答案:

答案 0 :(得分:4)

你可以通过中间课来完成。编译器本身不会做两次隐式转换,所以你必须做一次显式转换,然后编译器会找出第二个。

问题在于,使用隐式强制转换,您必须将转换为转换为您声明强制转换的类型,并且您不能继承密码类,例如&# 39; INT'

所以,它根本不优雅。扩展方法可能更优雅。

如果您声明下面的课程,则可以执行以下操作:

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

答案 1 :(得分:3)

你可以创建一些扩展方法来清理一下调用代码 - 所以你最终会得到:

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

 arr = i.ToByteArray();
 arr = a.ToByteArray();

扩展方法的代码如下:

public static class ExtensionMethods
    {
        public static byte[] ToByteArray(this int i)
        {
            return BitConverter.GetBytes(i);
        }

        public static byte[] ToByteArray(this float a)
        {
            return BitConverter.GetBytes(a);
        }
    }