C# xml可序列化多值枚举
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# xml可序列化多值枚举相关的知识,希望对你有一定的参考价值。
代码:
using System; using System.Collections.Generic; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace Hont { [XmlRoot("SerizlizableMultipleValueEnum"), Serializable] public class SerizlizableMultipleValueEnum<TEnum> : IXmlSerializable where TEnum : IConvertible { TEnum mEnumValue; public TEnum EnumValue { get { return mEnumValue; } } public SerizlizableMultipleValueEnum() { } public SerizlizableMultipleValueEnum(TEnum enumValue) { this.mEnumValue = enumValue; } #region IXmlSerializable Members public XmlSchema GetSchema() { return null; } public void ReadXml(XmlReader reader) { var typeSer = new XmlSerializer(typeof(int)); bool wasEmpty = reader.IsEmptyElement; reader.Read(); if (wasEmpty) return; while (reader.NodeType != XmlNodeType.EndElement) { reader.ReadStartElement("EnumValue"); mEnumValue = (TEnum)typeSer.Deserialize(reader); reader.ReadEndElement(); reader.MoveToContent(); } reader.ReadEndElement(); } public void WriteXml(XmlWriter writer) { var typeSer = new XmlSerializer(typeof(int)); writer.WriteStartElement("EnumValue"); typeSer.Serialize(writer, Convert.ToInt32(mEnumValue)); writer.WriteEndElement(); } #endregion } }
使用:
mTestValue = new SerizlizableMultipleValueEnum<MyEnum>(MyEnum.Value1 | MyEnum.Value2); var str = XmlSerializationHelper.SerializationToString(mTestValue); Console.WriteLine(str); mTestValue = XmlSerializationHelper.DeSerializationFromString<SerizlizableMultipleValueEnum<MyEnum>>(str); Console.WriteLine(mTestValue.EnumValue); //print 6.(value1 is 2, value2 is 4)
其他扩展:
可序列化接口:http://www.cnblogs.com/hont/p/4162448.html
序列化助手类:http://www.cnblogs.com/hont/p/3959854.html
以上是关于C# xml可序列化多值枚举的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 C# 中的 System.Xml.Serialization 使对象不可变但可序列化?
将xml反序列化为c#中的类时从XmlTextAttribute获取int值