【发布时间】: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