Generic enum parsing

pull/430/head
NextTurn 2020-03-01 00:00:00 +08:00
parent 2d1ffbacfa
commit e843c5c89c
No known key found for this signature in database
GPG Key ID: 17A0D50ADDE1A0C4
1 changed files with 12 additions and 1 deletions

View File

@ -87,22 +87,33 @@ namespace winsw.Util
/// <returns>Attribute value (or default)</returns> /// <returns>Attribute value (or default)</returns>
/// <exception cref="InvalidDataException">Wrong enum value</exception> /// <exception cref="InvalidDataException">Wrong enum value</exception>
public static TAttributeType EnumAttribute<TAttributeType>(XmlElement node, string attributeName, TAttributeType defaultValue) public static TAttributeType EnumAttribute<TAttributeType>(XmlElement node, string attributeName, TAttributeType defaultValue)
where TAttributeType : struct
{ {
if (!node.HasAttribute(attributeName)) if (!node.HasAttribute(attributeName))
return defaultValue; return defaultValue;
string rawValue = node.GetAttribute(attributeName); string rawValue = node.GetAttribute(attributeName);
string substitutedValue = Environment.ExpandEnvironmentVariables(rawValue); string substitutedValue = Environment.ExpandEnvironmentVariables(rawValue);
#if NET20
try try
{ {
var value = Enum.Parse(typeof(TAttributeType), substitutedValue, true); var value = Enum.Parse(typeof(TAttributeType), substitutedValue, true);
return (TAttributeType)value; return (TAttributeType)value;
} }
catch (Exception ex) // Most likely ArgumentException catch (ArgumentException ex)
{ {
throw new InvalidDataException("Cannot parse <" + attributeName + "> Enum value from string '" + substitutedValue + throw new InvalidDataException("Cannot parse <" + attributeName + "> Enum value from string '" + substitutedValue +
"'. Enum type: " + typeof(TAttributeType), ex); "'. Enum type: " + typeof(TAttributeType), ex);
} }
#else
if (!Enum.TryParse(substitutedValue, true, out TAttributeType result))
{
throw new InvalidDataException("Cannot parse <" + attributeName + "> Enum value from string '" + substitutedValue +
"'. Enum type: " + typeof(TAttributeType));
}
return result;
#endif
} }
} }
} }