2

我正在尝试将保存方法添加到可以调用并将对象序列化到文件的列表中。除了如何获取基类本身之外,我已经弄清楚了一切。

这是我的代码:

/// <summary>
/// Inherits the List class and adds a save method that writes the list to a stream.
/// </summary>
/// <typeparam name="T"></typeparam>
class fileList<T> : List<T>
{
    private static IFormatter serial = new BinaryFormatter();
    private Stream dataStream;

    /// <summary>
    /// path of the data file.
    /// </summary>
    public string dataFile { get; set; }
    /// <summary>
    /// Sets the datafile path
    /// </summary>
    public fileList(string dataFile)
    {
        this.dataFile = dataFile;
    }
    /// <summary>
    /// Saves the list to the filestream.
    /// </summary>
    public void Save()
    {
        dataStream = new FileStream(dataFile,
            FileMode.Truncate, FileAccess.Write,
            FileShare.Read);
        //Right here is my problem. How do I access the base class instance.
        serial.Serialize(dataStream, this.base); 
        dataStream.Flush();
        dataStream.Close();
        dataStream = null;
    }
}
4

1 回答 1

4

线

serial.Serialize(dataStream, this.base); 

应该只是

serial.Serialize(dataStream, this); 

但是请注意(感谢@Anders)这也将序列化string dataFile。为避免这种情况,请使用NonSerializedAttribute装饰该属性。

话虽如此,我更喜欢将这种类型的功能实现为静态方法。随着扩展方法的出现,我创建了一个小型扩展类来处理任何可序列化类型:

static public class SerialHelperExtensions
{
    static public void Serialize<T>(this T obj, string path)
    {
        SerializationHelper.Serialize<T>(obj, path);
    }
}

static public class SerializationHelper
{
    static public void Serialize<T>(T obj, string path)
    {

        DataContractSerializer s = new DataContractSerializer(typeof(T));
        using (FileStream fs = File.Open(path, FileMode.Create))
        {
            s.WriteObject(fs, obj);
        }
    }

    static public T Deserialize<T>(string path)
    {
        DataContractSerializer s = new DataContractSerializer(typeof(T));
        using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
        {
            object s2 = s.ReadObject(fs);
            return (T)s2;
        }
    }
}

您当然可以替代BinaryFormatterDataContractSerializer使用相同的模式。

于 2012-07-14T18:02:34.480 回答