gpt4 book ai didi

c# - XmlSerializer 奇怪的东西

转载 作者:行者123 更新时间:2023-11-30 19:47:24 27 4
gpt4 key购买 nike

对不起我的英语。我有 XmlSerializer 的奇怪之处。这是我的代码

[Serializable]
public class Radio
{
public bool hasSubWoofers;
public double[] stationPresets;

[XmlIgnoreAttribute]
public string radioId = "X-3454";
}

[Serializable]
public class Car
{
public Radio radio = new Radio();
public int speed;
}

[Serializable]
public class JamesBondCar : Car
{
public bool canFly;
public bool canSubmerge;

private string flag = "string flag";
}

JamesBondCar 类具有私有(private)成员“flag”,在序列化期间 XmlSerializer 不应对其进行序列化。在 XML 中,我正在寻找它。没有“标志”字段:

<JamesBondCar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<radio>
<hasSubWoofers>true</hasSubWoofers>
<stationPresets>
<double>192.3</double>
<double>45.2</double>
<double>456.3</double>
</stationPresets>
</radio>
<speed>342</speed>
<canFly>true</canFly>
<canSubmerge>false</canSubmerge>
</JamesBondCar>

但是,这是主要功能:

            JamesBondCar bond = new JamesBondCar();
bond.canFly = true;
bond.canSubmerge = false;
bond.speed = 342;
bond.radio.hasSubWoofers = true;
bond.radio.stationPresets = new double[] { 192.3, 45.2, 456.3 };
bond.radio.radioId = "Y-3424";

FileStream fs = new FileStream("car.xml", FileMode.Create, FileAccess.Write);
XmlSerializer serializer = new XmlSerializer(typeof(JamesBondCar));
serializer.Serialize(fs, bond);
fs.Close();

FileStream fs2 = new FileStream("car.xml", FileMode.Open, FileAccess.Read);
JamesBondCar jcar = (JamesBondCar)serializer.Deserialize(fs2);

在调试中序列化后,我可以在 jcar 实例的“标志”字段中找到它,它具有“字符串标志”值。这怎么可能? XML 没有这个值。

最佳答案

任何具有此类默认值的私有(private)成员字段都将在构造对象时(即调用对象构造函数时)使用这些默认值进行初始化。

关于c# - XmlSerializer 奇怪的东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6938118/

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