Reputation: 97
I have enum class that looks like this:
public enum StupidEnum
{
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("01")]
Item01,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("01_1")]
Item01_1,
/// <remarks/>
[System.Xml.Serialization.XmlEnumAttribute("01_11")]
Item01_11,
}
And now I would like to get Item01_11 enum object by only giving 01_11 value. In other words I have value from Xml Enum Attribute and as a result I would need enum object to be returned.
Upvotes: 0
Views: 2085
Reputation: 2930
You can create a Utility class and method like below:
public static class EnumUtilities
{
public static T GetValueFromXmlEnumAttribute<T>(string value) where T : Enum
{
foreach (var field in typeof(T).GetFields())
{
if (Attribute.GetCustomAttribute(field,
typeof(XmlEnumAttribute)) is XmlEnumAttribute attribute)
{
if (attribute.Name == value)
return (T)field.GetValue(null);
}
else
{
if (field.Name == value)
return (T)field.GetValue(null);
}
}
throw new ArgumentException("Could not parse XmlEnumAttribute. Not found.", nameof(value));
}
And call it like:
var result = EnumUtilities.GetValueFromXmlEnumAttribute<StupidEnum>("01");
Upvotes: 0
Reputation: 2423
I have managed to get it working but it's not a very elegant solution. Since your attributes are dependent on XML serialization you'll need to read it that way. I'll post the working code, and the way I would recommend.
var testString = "01_1";
var xml = new XmlSerializer(typeof(StupidEnum));
// XmlSerializer expects XML so wrap what you got in xml tags.
using(var ms = new MemoryStream(Encoding.ASCII.GetBytes($"<StupidEnum>{testString}</StupidEnum>")))
var item = (StupidEnum)xml.Deserialize(ms);
Console.WriteLine(item);
}
Alternatively, you can cast the enum
to an integral type and store that number then cast back to your enum
when reading or use the enumerations own ability to parse a string and not rely on the xml serialization values as follows:
var testString = "Item01_1";
// you can also just get the 01_1 and concatenate it to "Item" when parsing in the next line
var value = Enum.Parse(typeof(StupidEnum), testString);
Console.WriteLine(value);
Upvotes: 1