我正在创建一个方法,使用以下代码对文件进行序列化:
public void Save(Object file, Type type, String path)
{
// Create a new Serializer
XmlSerializer serializer = new XmlSerializer(typeof(type));
// Create a new StreamWriter
StreamWriter writer = new StreamWriter(@path);
// Serialize the file
serializer.Serialize(writer, file);
// Close the writer
writer.Close();
}
当我尝试构建时,Visual Studio告诉我:
"错误 1 找不到 'type' 类型或命名空间名称(是否缺少 using 指令或程序集引用?)c:\users\erik\documents\visual studio 2013\Projects\FileSerializer\FileSerializer\Class1.cs 16 65 FileSerializer"
为什么会这样呢?
**编辑*
新的可行代码:
public void Save(Object file, String path, Type type)
{
// Create a new Serializer
XmlSerializer serializer = new XmlSerializer(type);
// Create a new StreamWriter
TextWriter writer = new StreamWriter(path);
// Serialize the file
serializer.Serialize(writer, file);
// Close the writer
writer.Close();
}
public object Read(String path, Type type)
{
// Create a new serializer
XmlSerializer serializer = new XmlSerializer(type);
// Create a StreamReader
TextReader reader = new StreamReader(path);
// Deserialize the file
Object file;
file = (Object)serializer.Deserialize(reader);
// Close the reader
reader.Close();
// Return the object
return file;
}
通过调用以下代码进行读取:
myClass newClass = (myClass)Read(file, type);
通过调用实现节省:
Save(object, path, type);
谢谢! Erik