gpt4 book ai didi

c# - C#访问基类数据的方法

转载 作者:行者123 更新时间:2023-11-30 21:05:48 45 4
gpt4 key购买 nike

我正在尝试向 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;
}
}

最佳答案

线

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 并使用相同的模式。

关于c# - C#访问基类数据的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11486082/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com