mirror of https://github.com/winsw/winsw
Generic enum parsing
parent
2d1ffbacfa
commit
e843c5c89c
|
@ -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
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue