From e843c5c89c1d755b596d0fcbacff4e85145c32e2 Mon Sep 17 00:00:00 2001
From: NextTurn <45985406+NextTurn@users.noreply.github.com>
Date: Sun, 1 Mar 2020 00:00:00 +0800
Subject: [PATCH] Generic enum parsing
---
src/Core/WinSWCore/Util/XmlHelper.cs | 13 ++++++++++++-
1 file changed, 12 insertions(+), 1 deletion(-)
diff --git a/src/Core/WinSWCore/Util/XmlHelper.cs b/src/Core/WinSWCore/Util/XmlHelper.cs
index feedd40..5e79db1 100644
--- a/src/Core/WinSWCore/Util/XmlHelper.cs
+++ b/src/Core/WinSWCore/Util/XmlHelper.cs
@@ -87,22 +87,33 @@ namespace winsw.Util
/// Attribute value (or default)
/// Wrong enum value
public static TAttributeType EnumAttribute(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
}
}
}