Merge pull request #430 from NextTurn/enum

Use generic enum parsing methods in all packages except .NET 2.0
pull/450/head
Oleg Nenashev 2020-03-11 12:04:51 +01:00 committed by GitHub
commit dbb8efe410
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 1 deletions

View File

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