gpt4 book ai didi

c# - 序列化接口(interface)

转载 作者:可可西里 更新时间:2023-11-01 08:51:10 25 4
gpt4 key购买 nike

我正在尝试运行与此类似的代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
[Serializable]
[XmlInclude(typeof(List<Class2>))]
public class Class1
{
private IList<Class2> myArray;

public IList<Class2> MyArray
{
get { return myArray; }
set { myArray = value; }
}

}

public class Class2
{
private int myVar;

public int MyProperty
{
get { return myVar; }
set { myVar = value; }
}

}

class Program
{
static void Main(string[] args)
{
XmlSerializer ser = new XmlSerializer(typeof(Class1), new Type[] { typeof(List<Class2>) });
FileStream stream = File.OpenWrite("Data.xml");
ser.Serialize(stream, new List<Class1>());
stream.Close();
}
}
}

有人可以向我解释我做错了什么吗?

我得到一个:

无法序列化成员 .. MyArray ...,因为它是一个接口(interface)。

XmlInclude 不应该解决这个问题吗?

最佳答案

没有。您不能序列化接口(interface)。曾经。它只是告诉你。

界面只不过是一组行为的描述。它没有说明实例的内容。特别是,虽然实现接口(interface)的类的实例必须实现其所有成员,但它肯定会有自己的属性需要序列化。

如何反序列化?

将使用什么类来反序列化另一端的接口(interface)?

关于c# - 序列化接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4659248/

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