[英]C# Implicit/Explicit Byte Array Conversion
我有以下问题。 我想将整数值或浮点值转换为字节数组。 通常,我使用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;
您可以通过中间类来实现。 编译器本身不会执行两个隐式强制转换,因此您必须执行一个显式强制转换,然后编译器将找出第二个隐式强制转换。
问题是,与隐式类型转换,则必须强制转换或 从声明中投的类型,你无法从密封类像“诠释”继承。
因此,它一点也不优雅。 扩展方法可能更优雅。
如果在下面声明该类,则可以执行以下操作:
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};
}
}
您可以创建扩展方法来稍微清理调用代码-因此最终得到:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.