瀏覽代碼

Merge pull request #430 from NextTurn/enum

Use generic enum parsing methods in all packages except .NET 2.0
Oleg Nenashev 5 年之前
父節點
當前提交
dbb8efe410
共有 1 個文件被更改,包括 12 次插入1 次删除
  1. 12 1
      src/Core/WinSWCore/Util/XmlHelper.cs

+ 12 - 1
src/Core/WinSWCore/Util/XmlHelper.cs

@@ -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
         }
     }
 }