gpt4 book ai didi

c# - Upcast/Downcast 和序列化

转载 作者:行者123 更新时间:2023-11-30 14:11:55 28 4
gpt4 key购买 nike

只是玩类型转换。假设,我们有 2 个类

public class Base
{
public int a;
}

public class Inh : Base
{
public int b;
}

实例化它们

        Base b1 = new Base {a = 1};
Inh i1 = new Inh {a = 2, b = 2};

现在,让我们尝试上行

        // Upcast
Base b2 = i1;

似乎 b2 仍然持有字段 b,它仅在 Inh 类中出现。让我们通过向下转换来检查它。

        // Downcast
var b3 = b2;
var i2 = b2 as Inh;
var i3 = b3 as Inh;

bool check = (i2 == i3);

这里检查为真(我猜,因为 i2 和 i3 引用同一个实例 i1)。好的,让我们看看如何将它们存储在数组中。

        var list = new List<Base>();

list.Add(new Base {a = 5});
list.Add(new Inh {a = 10, b = 5});

int sum = 0;
foreach (var item in list)
{
sum += item.a;
}

一切正常,因为总和是 15。但是当我尝试使用 XmlSerializer 序列化数组时(只是为了看看里面有什么),它返回 InvalidOperationException“类型 ConsoleApplication1.Inh 不是预期的”。好吧,很公平,因为它有一系列的 Bases。

那么,b2 究竟是什么?我可以序列化一组 Bases 和 Inhs 吗?我可以通过向下转换反序列化数组中的项来获取 Inhs 字段吗?

最佳答案

如果你想让它与序列化一起工作,你需要告诉序列化器关于继承。对于 XmlSerializer,这是:

[XmlInclude(typeof(Inh))]
public class Base
{
public int a;
}

public class Inh : Base
{
public int b;
}

然后下面的工作正常:

var list = new List<Base>();

list.Add(new Base { a = 5 });
list.Add(new Inh { a = 10, b = 5 });

var ser = new XmlSerializer(list.GetType());
var sb = new StringBuilder();
using (var xw = XmlWriter.Create(sb))
{
ser.Serialize(xw, list);
}
string xml = sb.ToString();
Console.WriteLine(xml);
using (var xr = XmlReader.Create(new StringReader(xml)))
{
var clone = (List<Base>)ser.Deserialize(xr);
}

clone 具有预期的 2 个不同类型的对象。 xml 是(为了便于阅读而重新格式化):

<?xml version="1.0" encoding="utf-16"?><ArrayOfBase
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Base><a>5</a></Base>
<Base xsi:type="Inh"><a>10</a><b>5</b></Base>
</ArrayOfBase>

关于c# - Upcast/Downcast 和序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18955782/

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