【问题标题】:How to get byte array in a fuction whose parameters are generic in c#?如何在c#中参数是通用的函数中获取字节数组?
【发布时间】:2018-03-27 12:27:24
【问题描述】:

我想给函数提供intshortSingleDouble。我希望一个数组以相反的顺序返回。

喜欢

  • fun(2.0f) 将返回 [0x40, 0, 0, 0]

  • fun(0x01020304) 将返回 [1, 2, 3, 4]

  • fun( (short) 0x0102) 将返回 [1, 2]

我试过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.

【问题讨论】:

    标签: c# arrays type-conversion endianness


    【解决方案1】:

    你看过BitConverter吗?

    也就是说,泛型并不适合采用“原始”类型的方法。没有T: PrimitiveT: Numeric 约束。您可以做的最好的事情是T: struct,但这是一个非常微弱的努力。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-03
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多