I'm pretty sure things will work better if every case in a switch
expression returns a consistent type. They casts you show are superfluous. Each of those BitConverter calls returns the type you expect.
But, remember, each of those things ends up being boxed as an object
at some point in your code. It's probably better if you specify when and how that boxing takes place. Consider something like this instead:
object value = header.DataContentType switch
{
DataContentType.DOUBLE => (object)BitConverter.ToDouble(currentValueBytes.ToArray()),
DataContentType.FLOAT => (object)BitConverter.ToSingle(currentValueBytes.ToArray()),
DataContentType.BYTE => (object)contentData[i],
DataContentType.SHORT => (object)BitConverter.ToInt16(currentValueBytes.ToArray()),
DataContentType.INTEGER => (object)BitConverter.ToInt32(currentValueBytes.ToArray()),
DataContentType.LONG => (object)BitConverter.ToInt64(currentValueBytes.ToArray()),
_ => throw new InvalidDataException("Invalid data type"),
};
I'm intrigued how you are going to consume value
at this point. Unboxing is a delicate operation. The only time I've ever done something like this is upstream of a JSON-ification operation (where the Newtonsoft JSON package if very happy serializing boxed native value types).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…