Convert byte array to generic value type?

后端 未结 1 1201
借酒劲吻你
借酒劲吻你 2021-01-23 06:08

I have a Stream where I\'d like to read data from (as value type segments) and move the position according to the size of the given type (declared as generics).

1条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-23 06:33

    return (TValue)buffer; // here's where I'm stuck
    

    Yes, you have just shifted the problem. From not having a Stream.Read() to not having a Convert(byte[]) in the std library.
    And you would have to call it like Read() anyway so there isn't a direct advantage over BinaryReader.ReadInt32()

    Now when you want to use it from another generic class/method, the Read() syntax is useful but for the implementation you might as well map it to BinaryReader calls. I'm afraid that will require boxing:

    obcject result = null;
    if (typeof(TValue) == typeof(int))
      result = reader.ReadInt32();
    else if (typeof(TValue) == typeof(double))
      result = reader.ReadDouble();
    else ...
    
    return (TValue) result;
    

    0 讨论(0)
提交回复
热议问题