[英]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.