我正在使用 Activator(C#) 动态创建对象,其中一个类如下所示:
class Driver
{
Driver() { }
[XmlChoiceIdentifier("ItemElementName")]
[XmlElement("Bit16", typeof(DriverModule))]
[XmlElement("Bit32", typeof(DriverModule))]
[XmlElement("Bit64", typeof(DriverModule))]
[XmlElement("Unified", typeof(DriverUnified))]
public object Item { get; set; }
[XmlIgnore]
public ItemChoiceType ItemElementName { get; set; }
// ... other serialization methods
}
当我使用 Activator 创建 Driver 类的实例时,我得到以下对象:
obj.Item = null;
obj.ItemElementName = "Bit16"
ItemElementName 是默认设置的,因为它是枚举,但是如果它基于此枚举,如何设置 Item?
再次,我使用 Activator 动态创建许多对象,因此我无法对其进行硬编码 - 是否可以在类中获取此信息并正确创建 Item 属性?
多谢!
ItemElementName
被设定为ItemChoiceType.Bit16
因为这是枚举中的第一项。因此它的值是0
但你可以将其视为Bit16
. By 活化剂您创建一个新实例。如果您不添加参数来设置属性,那么它们的值将是默认值。
我看到您有 XmlChoiceIdentifier 和其他 XmlSerializer 的东西。该属性的目的是:
- 不要序列化
ItemElementName
财产。
- 恢复
ItemElementName
根据序列化值进行反序列化后Item
.
这就是我根据给定的信息可以告诉你的......
以下是使用 XmlSerializer 和 XmlChoiceIdentifier 的示例:
public class Choices
{
[XmlChoiceIdentifier("ItemType")]
[XmlElement("Text", Type = typeof(string))]
[XmlElement("Integer", Type = typeof(int))]
[XmlElement("LongText", Type = typeof(string))]
public object Choice { get; set; }
[XmlIgnore]
public ItemChoiceType ItemType;
}
[XmlType(IncludeInSchema = false)]
public enum ItemChoiceType
{
Text,
Integer,
LongText
}
class Program
{
static void Main(string[] args)
{
Choices c1 = new Choices();
c1.Choice = "very long text"; // You can put here a value of String or Int32.
c1.ItemType = ItemChoiceType.LongText; // Set the value so that its type match the Choice type (Text or LongText due to type of value is string).
var serializer = new XmlSerializer(typeof(Choices));
using (var stream = new FileStream("Choices.xml", FileMode.Create))
serializer.Serialize(stream, c1);
// Produced xml file.
// Notice:
// 1. LongText as element name
// 2. Choice value inside the element
// 3. ItemType value is not stored
/*
<?xml version="1.0"?>
<Choices xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<LongText>very long text</LongText>
</Choices>
*/
Choices c2;
using (var stream = new FileStream("Choices.xml", FileMode.Open))
c2 = (Choices)serializer.Deserialize(stream);
// c2.ItemType is restored
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)