[英]C# LINQ to XML: "Safe" enum value from an XElement?
To get a "safe" integer value from an XElement in C# one can use a method like要从 C# 中的 XElement 获取“安全”整数值,可以使用类似的方法
public int GetIntegerValue(XElement x, string tag)
{
int result = Int32.MinValue;
if (x.Element(tag) != null)
{
Int32.TryParse(x.Element(tag).Value, out result);
}
return result;
}
The code returns the correct integer value if the element is present and contains a parseable string, otherwise Int32.MinValue.如果元素存在且包含可解析字符串,则代码返回正确的整数值,否则返回 Int32.MinValue。 This approach would function with a few other common types like double, bool, etc., but what about enum?
这种方法适用于其他一些常见类型,如 double、bool 等,但 enum 呢?
Can there also be a function like GetEnumValue(XElement x, string tag, Type enumType) or GetEnumValue(XElement x, string tag, TEnum defaultValue) or alike?也可以有像 GetEnumValue(XElement x, string tag, Type enumType) 或 GetEnumValue(XElement x, string tag, TEnum defaultValue) 之类的函数吗?
You can try following method:您可以尝试以下方法:
public static TEnum GetEnumValue<TEnum>(XElement x, string tag)
where TEnum : struct
{
// Set default value
TEnum parsedEnum = default(TEnum);
var element = x.Element(tag);
if(element != null)
{
// Try to parse
Enum.TryParse<TEnum>(element.Value, out parsedEnum);
}
return parsedEnum;
}
And then call it like:然后这样称呼它:
CarType carType = GetEnumValue<CarType>(xElement, tag);
You can CAST an ENUM to an integer.您可以将 ENUM 强制转换为整数。 Also you can use the .ToString() to help Identify the enum types.
您也可以使用 .ToString() 来帮助识别枚举类型。
Try this code below - it is very quick, but it does work.试试下面的代码 - 它非常快,但确实有效。
using System;
using System.Xml;
using System.Xml.Linq;
public class Program
{
public enum testTypes { test1, test2, test3};
private static testTypes GetEnumValue(XElement x, string tag)
{
if (x.Element(tag)!=null) {
var v = x.Element(tag).Value.ToString();
var testEnums = Enum.GetValues(typeof(testTypes));
foreach (testTypes enumType in testEnums) {
if (v.Equals((testTypes) enumType)) return enumType;
}
}
return (testTypes) 0;
}
public static void Main()
{
XElement x = new XElement("MyType","Test1");
var EnumVal = GetEnumValue(x, "MyType");
Console.WriteLine("Type is {0}",(testTypes) EnumVal);
}
}
You could actually use Generics to generalise the approach instead of using the static Method.您实际上可以使用泛型来概括该方法,而不是使用静态方法。
Working with previous Adil, one can also create an extension function as follow :使用以前的 Adil,还可以创建一个扩展函数,如下所示:
public static TEnum ToEnumValue<TEnum>(this XElement xelem)
where TEnum : struct
{
if (xelem is null)
{
throw new ArgumentNullException(nameof(xelem));
}
Enum.TryParse<TEnum>(xelem.Value, out TEnum parsedEnum);
return parsedEnum;
}
then it can be used as follow :那么它可以按如下方式使用:
MyViewModel.Mode = node.Element("MyMode")?.ToEnumValue<ModeEnum>() ?? ModeEnum.Mode1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.