如何在c#中访问基类数据

时间:2012-07-14 17:59:52

标签: c# .net-4.0

我正在尝试将一个save方法添加到我可以调用的List中,并将该对象序列化为一个文件。除了如何获得基类之外,我已经弄明白了。

这是我的代码:

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

1 个答案:

答案 0 :(得分: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;
        }
    }
}

您当然可以将BinaryFormatter替换为DataContractSerializer并使用相同的模式。