【问题标题】:casting to multiple (unknown types) at runtime在运行时转换为多个(未知类型)
【发布时间】:2010-10-11 18:38:33
【问题描述】:

我正在开发一个查看器,它能够打开我们通过我们的软件生成的所有自定义文档。所有文档都继承自 IDocument,但我不确定如何进行反序列化(以一种好的方式 - 嵌套的 try/catch 可能会起作用,但这会很可怕)。

所以我的方法现在看起来像这样:

public Boolean OpenDocument(String filename, Type docType, out IDocument document)
{
    // exception handling etc. removed for brevity

    FileStream fs = null;
    BinaryFormatter bFormatter = new BinaryFormatter();

    fs = new FileStream(filename, FileMode.Open);
    document = (docType)bFormatter.Deserialize(fs);

    return true;
}

显然这不起作用,因为我不能那样使用变量 docType,但我认为它说明了我正在尝试做的事情。这样做的正确方法是什么?

编辑> @约翰 好的,也许我应该附加另一个问题: 如果我有接口:

public interface IDocument
{
    public Int32 MyInt { get; }
}

还有一个班级:

public class SomeDocType : IDocument
{
    protected Int32 myInt = 0;
    public Int32 MyInt { get { return myint; } }

    public Int32 DerivedOnlyInt;
}

如果我反序列化为 IDocument,那么 DerivedOnlyInt 是否会成为对象的一部分 - 这样在反序列化之后,我可以转换为 SomeDocType 并且会没问题?

【问题讨论】:

    标签: c# types serialization


    【解决方案1】:

    为什么不直接转换为IDocument?您认为在这里转换为确切的类型有什么好处?

    如果您希望调用者以强类型的方式获取结果,我将使用泛型来编写它:

    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);
        }
    }
    

    当然,这依赖于调用者在编译时知道正确的类型。如果他们不这样做,他们无论如何也不可能知道如何使用正确的类型,所以只需返回IDocument:

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

    编辑:要回答对您问题的编辑,是的,派生属性仍然存在。强制转换实际上并没有改变一个对象——它只是意味着你得到了一个编译器知道是适当类型的引用。

    【讨论】:

    • 我使用通用方法来包装我的序列化函数。恕我直言,这是最好的方法
    • 非常好。在这种情况下,调用者确实知道文档类型(通过 openfiledialog 中的文件扩展名)。谢谢乔恩
    • @Jon 这似乎不适用于 XmlSerialization。我能够得到一个有效但感觉有点笨拙的问题和答案,我们是否遗漏了什么:stackoverflow.com/questions/1145791/…
    【解决方案2】:

    您正在使用将类型信息包含到序列化流中的 BinaryFormatter 类,因此您不需要 docType 变量:

    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;
    }
    

    【讨论】:

      【解决方案3】:

      如果您可以轻松找出它是什么类型的文档(即:它是文件头的一部分),那么使用strategy 来针对每种类型进行反序列化可能是最简单的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多