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

The line

serial.Serialize(dataStream, this.base); 

should just be

serial.Serialize(dataStream, this); 

Note however (thanks @Anders) that this will also serialize string dataFile. To avoid that, decorate that property with NonSerializedAttribute.

Having said that, I prefer to implement this type of functionality as a static method. With the advent of extension methods, I created a small extension class to handle this for any serializable type:

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

You can certainly substitute BinaryFormatter for DataContractSerializer and use the same pattern.

于 2012-07-14T18:02:34.480 に答える