如何在 C# 中参数为泛型的函数中获取字节数组?

How to get byte array in a fuction whose parameters are generic in c#?

我想给函数 intshortSingleDouble。我想要一个数组以相反的顺序 return。

喜欢

我试过了Convert any object to a byte[]

但是我无法实现我的目标。这个函数能不能写成通用的<T>类型我会很想学习的

public static byte[] fun(object obj)
{
    if (obj == null)
        return null;
    BinaryFormatter bf = new BinaryFormatter();
    using (MemoryStream ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);                
        byte[] ar = ms.ToArray();
        Array.Reverse(ar);
        return ar;
    }
}

在@InBetween 的回答后,我的代码在下面并且工作正常。

    public static byte[] Reverse(byte[] ar )
    {
        Array.Reverse(ar);
        return ar;
    }
    Reverse(BitConverter.GetBytes(2.0f);// gives me [0x40, 0, 0, 0] in a single line.

你看过BitConverter了吗?

也就是说,泛型不适合采用 "primitive" 类型的方法。没有 T: PrimitiveT: Numeric 约束。你能做的最好的事情就是 T: struct,但这是一项非常薄弱的​​努力。

此外,泛型意味着对于给定的泛型方法应该有无限数量的有效类型,这就是为什么它......好吧,泛型。如果您的类型集是有限的,甚至只有少数类型,那么您没有使用正确的工具来完成这项工作。

所以,总结一下,如果您确实知道您需要支持的类型,解决这个问题的正确方法是使用方法重载,BitConverter.GetBytes就是这样做的。