Is there a way cast an object back to it original type without specifing every case?

前端 未结 6 1408
眼角桃花
眼角桃花 2021-01-15 14:28

I have an array of different type objects and I use a BinaryWriter to convert each item to its binary equivalent so I can send the structure over the network.

I curr

6条回答
  •  無奈伤痛
    2021-01-15 15:19

    No. The cast has to be known at compile-time, but the actual type is only known at execution time.

    Note, however, that there's a better way of testing the type calling GetType. Instead of:

    if (x.GetType() == typeof(byte))
    

    Use:

    if (x is byte)
    

    EDIT: To answer the extra questions:

    "What are all the types?" Well, look down the docs for BinaryWriter, I guess...

    "Do I need to worry about byte and Byte?" No, byte is an alias for System.Byte in C#. They're the same type.

提交回复
热议问题