casting to multiple (unknown types) at runtime

前端 未结 3 816
春和景丽
春和景丽 2021-01-03 15:24

I\'m developing a viewer that will be able to open all of the custom documents that we produce via our software. All of the documents inherit from IDocument, but I\'m not su

相关标签:
3条回答
  • 2021-01-03 15:38

    Why not just cast to IDocument? What benefit do you believe casting to the exact type would have here?

    If you want the caller to get the result in a strongly typed way, here's how I'd write it, using generics:

    public T OpenDocument<T>(String filename) where T : IDocument
    {
        using (FileStream fs = new FileStream(filename, FileMode.Open))
        {
            BinaryFormatter bFormatter = new BinaryFormatter();    
            return (T) bFormatter.Deserialize(fs);
        }
    }
    

    Of course, that relies on the caller knowing the right type at compile-time. If they don't, there's no way they're going to know how to use the right type anyway, so just return IDocument:

    public IDocument OpenDocument(String filename)
    {
        using (FileStream fs = new FileStream(filename, FileMode.Open))
        {
            BinaryFormatter bFormatter = new BinaryFormatter();    
            return (IDocument) bFormatter.Deserialize(fs);
        }
    }
    

    EDIT: To answer the edit to your question, yes the derived property would still exist. Casting doesn't actually change an object - it just means you get a reference which the compiler knows is of an appropriate type.

    0 讨论(0)
  • 2021-01-03 15:39

    You are using the BinaryFormatter class which includes type information into the serialized stream, so you don't need the docType variable:

    public Boolean OpenDocument(String filename, out IDocument document)
    {
        // exception handling etc. removed for brevity
    
        FileStream fs = null;
        BinaryFormatter bFormatter = new BinaryFormatter();
    
        fs = new FileStream(filename, FileMode.Open);
        document = (IDocument)bFormatter.Deserialize(fs);
    
        return true;
    }
    
    0 讨论(0)
  • 2021-01-03 15:57

    If you can easily figure out what kind of document it is (ie: it's part of the file header), it might be easiest to have a strategy for deserializing that is specific to each type.

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