【发布时间】:2011-09-01 10:05:07
【问题描述】:
我之前问过How to save/restore serializable object to/from file? 的问题,当我知道要保存什么类型的对象时,该解决方案效果很好。
如果我能保存一个未知类型的对象就好了。
无论如何我都想做类似的事情:
[Serializable]
MyCustomClass
{
// properties. I don't know which properties this class has. I might pass a different class.
}
public void saveObjectInComputer(object obj, string pathWhereToSaveObject)
{
// code
}
public object deserializeObject(string pathWhereObjectIsLocated)
{
// code to retrive object
// ...
return object;
}
static void Main(string[] args)
{
List<MyCustomClass> myList = new List<MyCustomClass>();
myList.add(new MyCustomClass { "properties go here" } );
saveObjectInComputer(myList, @"C:\Temp\object.txt");
// code
// Later it will be nice if I could retrive the object
object a = deserializeObject(@"C:\Temp\object.txt");
// then cast a to List<MyCustomClass>
}
然后,如果我构建一个汽车列表或人员列表,我可以使用相同的方法,而不是为每个构建一个新方法。此外,后来我知道我正在寻找的方法将返回一个对象,我可以将该对象转换为我当前正在使用的类型。
【问题讨论】:
-
您不应编辑其他人的答案以包含有关您的问题的更多信息;您应该对答案发表评论,或再次编辑您的问题以包含其他信息。 (另外,请将较长的部分分成几段。:)
标签: c# serialization stream