gpt4 book ai didi

c# - 不需要实现 ISerializable 吗?

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:17 25 4
gpt4 key购买 nike

我很难理解 ISerializable 接口(interface)的必要性......我想我在这个主题中遗漏了一些非常重要的东西,所以如果有人能帮助我,我将不胜感激。

这很好用-

[Serializable]
class Student
{
public int age;
public string name;

public Student()
{
age = 0;
name = null;
}
}
class Program
{
public static void Main()
{
Stream stream = File.Open("Test123.txt", FileMode.Create);

BinaryFormatter bf = new BinaryFormatter();

Student s1 = new Student();
s1.name = "Peter";
s1.age = 50;
bf.Serialize(stream, s1);

stream.Close();

Stream stream2 = File.Open("Test123.txt", FileMode.Open);

Student s2 = (Student)bf.Deserialize(stream2);

Console.WriteLine(s2.age);

}

它在没有实现 ISerializable 和覆盖 GetObjectData() 的情况下工作。为何如此?那这个接口(interface)有什么用呢?

谢谢。

最佳答案

Serializable 使用默认序列化。 ISerializable 接口(interface)的要点是覆盖序列化,以便您可以拥有自己的序列化。

关于c# - 不需要实现 ISerializable 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19345352/

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