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

前端 未结 6 1410
眼角桃花
眼角桃花 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:08

    This is a case of needing something called Double Dispatch.

    I'm going to assume that the wrt object is one you wrote yourself (Let's say it is of type Writer). Here is what you could do:

    class Writer
    {
        void write(byte b)
        {
            // write bytes here
        }
    
        void write(Writable something)
        {
            something.writeOn(this);
        }
    }
    
    interface Writeable
    {
        void writeOn(Writer writer);
    }
    
    class SomeObject implements Writeable
    {
        private Object someData;
        private Object moreData;
    
        void writeOn(Writer writer)
        {
            writer.write(convertToByte(someData));
            writer.write(convertToByte(moreData));
        }
    }
    
    class AnotherObject implements Writeable
    {
        private int x;
        private int y;
        private int z;
    
        void writeOn(Writer writer)
        {
            writer.write((byte)x);
            writer.write((byte)y);
            writer.write((byte)z);
        }
    }
    

    What Writer is doing is dispatching back to the input, telling it to use it (the Writer) to write, however that is done for that object, which cannot be known ahead of time.

提交回复
热议问题