我想在 List 类上使用 GetBytes 扩展方法...
public static class Extensions
{
public static byte[] GetBytes<T>(this ICollection<T> col)
{
List<byte> bytes = new List<byte>();
foreach (T t in col)
bytes.AddRange(BitConverter.GetBytes(t));
return bytes.ToArray();
}
}
当我编译时,我收到一个编译器错误,指出 Argument '1': cannot convert from 'T' to 'double'。谁能给我解释一下这是什么问题?
最佳答案
BitConverter 没有 GetBytes适用于任意类型的实现。您必须传递正确类型的参数,例如 double、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 调用不那么“漂亮”,但它确实可以正常工作。这可以通过添加重载来为特定类型的 T 删除,例如:
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();
}
}
编辑:因为您需要避免 SelectMany,所以您可以像以前一样编写 main 函数。 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();
}
}
关于c# - 扩展方法和 GetBytes 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3098047/