c# - 扩展方法和 GetBytes 实现

标签 c# list extension-methods

我想在 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/

相关文章:

c# - Kinect错误启用流

python - 匹配两个部分匹配到另一个列表的字符串列表

c# - 如何从 List<T> 转换为 IList<T> 的子类型

c# - 带有 ref 的扩展方法不适用于数组

c# - 秒表计时异步/等待方法不准确

c# - 如何在 C# 中编写 XML?

c# - 加入 + IEqualityComparer<T> 和 HashCode

c# - 如何在 C# 中将 List<object> 转换为 Hashtable?

c# - 为不支持的类型列出的扩展方法。为什么?

ios - 如何在 View 上创建扩展以在长按手势上显示警报 - SwiftUI