BitConverter沒有GetBytes實現,在任意類型的作品。你必須通過正確的類型,如雙,int的參數等
編譯器沒有找到一個合適的過載,而「違約」的雙重過載保護,然後報告爲編譯器錯誤。
爲了對一般類型的使用,你還需要通過在轉換爲字節的Func鍵。這會工作:
public static class Extensions
{
public static byte[] GetBytes<T>(this IEnumerable<T> col, Func<T, byte[]> conversion)
{
return col.SelectMany(conversion).ToArray();
}
}
然後,您可以使用此類似:
static void Main(string[] args)
{
double[] test = new double[3]
{
0, 12, 14.12
};
List<int> ilist = new List<int>() { 3,5,1 };
byte[] doubles = test.GetBytes(BitConverter.GetBytes);
byte[] ints = ilist.GetBytes(BitConverter.GetBytes);
Console.WriteLine("Double collection as bytes:");
foreach (var d in doubles)
{
Console.WriteLine(d);
}
Console.WriteLine("Int collection as bytes:");
foreach (var i in ints)
{
Console.WriteLine(i);
}
Console.ReadKey();
}
不幸的是,「BitConverter.GetBytes」線(或其他一些函數來完成這種轉換),使API調用一點少「漂亮」,但它確實工作正常。
public static class Extensions
{
public static byte[] GetBytes(this IEnumerable<double> col)
{
return GetBytes<double>(col, BitConverter.GetBytes);
}
public static byte[] GetBytes(this IEnumerable<int> col)
{
return GetBytes<int>(col, BitConverter.GetBytes);
}
// Add others as needed
public static byte[] GetBytes<T>(this IEnumerable<T> col, Func<T, byte[]> conversion)
{
return col.SelectMany(conversion).ToArray();
}
}
編輯:這可能對特定類型的T加過載,如被刪除,因爲你需要避免的SelectMany,你可以只寫的主要功能您以前一樣的工作方式。 SelectMany只是使這個更簡單:
public static class Extensions
{
public static byte[] GetBytes<T>(this IEnumerable<T> col, Func<T, byte[]> conversion)
{
List<byte> bytes = new List<byte>();
foreach (T t in col)
bytes.AddRange(conversion(t));
return bytes.ToArray();
}
}
不幸的是,我不能使用SelectMany,因爲我在.CF平臺上運行...對不起,我應該提到這之前。任何建議來取代? – MQS 2010-06-23 14:38:07
@dirtmike:我剛剛編輯給你看 - 基本上,只是把你的原始代碼,但子。出Func;)它會正常工作。其他一切如上所述。 – 2010-06-23 15:49:46
我完全錯過了通用轉換的內容。非常感謝! – MQS 2010-06-23 17:17:53