Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 解析为可为空的枚举_C#_.net_Reflection_Enums_Nullable - Fatal编程技术网

C# 解析为可为空的枚举

C# 解析为可为空的枚举,c#,.net,reflection,enums,nullable,C#,.net,Reflection,Enums,Nullable,我试图将字符串解析回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,代码将正常工作 除

我试图将字符串解析回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,代码将正常工作

除了通过反射,我如何在不知道枚举类型的情况下让代码工作

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();
}
Type t=myEnumPropertyInfo.PropertyType;
if(t.GetGenericTypeDefinition()==typeof(可为空))
{
t=t.GetGenericArguments().First();
}

给你。一个字符串扩展名,可以帮助您完成此操作

    /// <summary>
    /// <para>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.
    /// </para>
    /// <para>
    /// 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. 
    /// </para>
    /// <author>Contributed by Taylor Love (Pangamma)</author>
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="p_self"></param>
    /// <returns></returns>
    public static T? ToNullable<T>(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<T>(p_self, out t)) return t;}
        }

        return null;
    }
//
///比使用T.TryParse(string,out T)更方便。
///使用基元类型、结构和枚举。
///尝试将字符串解析为指定类型的实例。
///如果无法解析输入,将返回null。
/// 
/// 
///如果调用方的值为null,则返回null。
///因此,如果您有“string s=null;”,然后尝试“s.ToNullable…”,
///将返回null。不会引发空异常。
/// 

///

我知道这是从2012年开始的,但对于任何偶然发现相同问题的人(如我),这是一个小小的改进:在t.GetGenericTypeDefinition()之前添加一个t.IsGenericType检查==…,否则代码可能会因不可为null的枚举类型而中断