解析为Nullable Enum
我试图将字符串解析回MyEnum类型的可空属性。
public MyEnum? MyEnumProperty { get; set; }
我在线收到错误:
Enum result = Enum.Parse(t, "One") as Enum; // Type provided must be an Enum. Parameter name: enumType
我在下面有一个示例控制台测试。 如果我在属性MyEntity.MyEnumProperty
上删除nullable,则代码有效。
除了通过reflection之外,如何在不知道typeOf枚举的情况下使代码工作?
static void Main(string[] args) { MyEntity e = new MyEntity(); Type type = e.GetType(); PropertyInfo myEnumPropertyInfo = type.GetProperty("MyEnumProperty"); Type t = myEnumPropertyInfo.PropertyType; Enum result = Enum.Parse(t, "One") as Enum; Console.WriteLine("result != null : {0}", result != null); Console.ReadKey(); } public class MyEntity { public MyEnum? MyEnumProperty { get; set; } } public enum MyEnum { One, Two } }
为Nullable
添加一个特例将起作用:
Type t = myEnumPropertyInfo.PropertyType; if (t.GetGenericTypeDefinition() == typeof(Nullable<>)) { t = t.GetGenericArguments().First(); }
干得好。 一个字符串扩展,可以帮助您。
/// /// More convenient than using T.TryParse(string, out T). /// Works with primitive types, structs, and enums. /// Tries to parse the string to an instance of the type specified. /// If the input cannot be parsed, null will be returned. /// /// /// If the value of the caller is null, null will be returned. /// So if you have "string s = null;" and then you try "s.ToNullable...", /// null will be returned. No null exception will be thrown. /// /// Contributed by Taylor Love (Pangamma) /// /// /// /// public static T? ToNullable(this string p_self) where T : struct { if (!string.IsNullOrEmpty(p_self)) { var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T)); if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self); if (typeof(T).IsEnum) { T t; if (Enum.TryParse (p_self, out t)) return t;} } return null; }
https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions