简体   繁体   中英

How to access the base class data in c#

I am trying to add a save method to a List that I can call and serialize the object to a file. I've got everything figured out except how to get the base class itself.

Here's my code:

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM