Save file - xmlSerializer

我与影子孤独终老i 提交于 2019-12-07 00:18:08

问题


I'm creating a method to serialize a file using this code:

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

But Visual Studio tells me this when I attempt to build: "Error 1 The type or namespace name 'type' could not be found (are you missing a using directive or an assembly reference?) c:\users\erik\documents\visual studio 2013\Projects\FileSerializer\FileSerializer\Class1.cs 16 65 FileSerializer "

Why is this?

**EDIT*

New code that works:

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

read by calling:

myClass newClass = (myClass)Read(file, type);

Save by calling:

Save(object, path, type);

Thanks! Erik


回答1:


Your error is in new XmlSerializer(typeof(type));. You don't need typeof. new XmlSerializer(type); is enough.

Since you serialize file object (and its type can be determined in the function) you don't have to pass its type. So your code can be re-written as

public void Save<T>(T file, String path)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));

    using (StreamWriter writer = new StreamWriter(path))
    {
        serializer.Serialize(writer, file);
    }
}



回答2:


var serializer = new System.Xml.Serialization.XmlSerializer(type);

instead of

XmlSerializer serializer = new XmlSerializer(typeof(type));



回答3:


XmlSerializer takes a Type parameter. type is already of type Type, so you don't need to call typeof() on it. typeof() is only needed when you're putting a class name or generic parameter inside the brackets.



来源:https://stackoverflow.com/questions/27177445/save-file-xmlserializer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!