简体   繁体   English

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

[英]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 . 但是请注意(感谢@Anders),这还将序列化string dataFile To avoid that, decorate that property with NonSerializedAttribute . 为了避免这种情况,请使用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. 您当然可以用BinaryFormatter代替DataContractSerializer并使用相同的模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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