将 Null 转换为可为 Null 的枚举(通用)

发布于 2024-09-25 08:32:14 字数 1139 浏览 3 评论 0原文

我正在编写一些枚举功能,并具有以下功能:

public static T ConvertStringToEnumValue<T>(string valueToConvert, 
    bool isCaseSensitive)
{
    if (String.IsNullOrWhiteSpace(valueToConvert))
        return (T)typeof(T).TypeInitializer.Invoke(null);

    valueToConvert = valueToConvert.Replace(" ", "");
    if (typeof(T).BaseType.FullName != "System.Enum" &&
        typeof(T).BaseType.FullName != "System.ValueType")
    {
        throw new ArgumentException("Type must be of Enum and not " +
            typeof (T).BaseType.FullName);
    }

    if (typeof(T).BaseType.FullName == "System.ValueType")
    {
        return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)),
            valueToConvert, !isCaseSensitive);
    }

    return (T)Enum.Parse(typeof(T), valueToConvert, !isCaseSensitive);
}

我现在用以下内容调用它:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>("Cat");

这按预期工作。但是,如果我运行此命令:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>(null);

它会因 TypeInitializer 为 null 的错误而中断。

有谁知道如何解决这个问题?

谢谢大家!

I'm writing some Enum functionality, and have the following:

public static T ConvertStringToEnumValue<T>(string valueToConvert, 
    bool isCaseSensitive)
{
    if (String.IsNullOrWhiteSpace(valueToConvert))
        return (T)typeof(T).TypeInitializer.Invoke(null);

    valueToConvert = valueToConvert.Replace(" ", "");
    if (typeof(T).BaseType.FullName != "System.Enum" &&
        typeof(T).BaseType.FullName != "System.ValueType")
    {
        throw new ArgumentException("Type must be of Enum and not " +
            typeof (T).BaseType.FullName);
    }

    if (typeof(T).BaseType.FullName == "System.ValueType")
    {
        return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)),
            valueToConvert, !isCaseSensitive);
    }

    return (T)Enum.Parse(typeof(T), valueToConvert, !isCaseSensitive);
}

I now call this with the following:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>("Cat");

This works as expected. However, if I run this:

EnumHelper.ConvertStringToEnumValue<Enums.Animals?>(null);

it breaks with the error that the TypeInitializer is null.

Does anyone know how to solve this?

Thanks all!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

非要怀念 2024-10-02 08:32:14

尝试

if (String.IsNullOrWhiteSpace(valueToConvert))
              return default(T);

try

if (String.IsNullOrWhiteSpace(valueToConvert))
              return default(T);
呆° 2024-10-02 08:32:14

我有一种不同的方法,使用扩展和泛型。

public static T ToEnum<T>(this string s) {
    if (string.IsNullOrWhiteSpace(s))
        return default(T);

    s = s.Replace(" ", "");
    if (typeof(T).BaseType.FullName != "System.Enum" &&
        typeof(T).BaseType.FullName != "System.ValueType") {
        throw new ArgumentException("Type must be of Enum and not " + typeof(T).BaseType.FullName);
    }

    if (typeof(T).BaseType.FullName == "System.ValueType")
        return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)), s, true);

    return (T)Enum.Parse(typeof(T), s, true);
}

像这样使用...

Gender? g = "Female".ToEnum<Gender?>();

I have an different approach, using extension and generics.

public static T ToEnum<T>(this string s) {
    if (string.IsNullOrWhiteSpace(s))
        return default(T);

    s = s.Replace(" ", "");
    if (typeof(T).BaseType.FullName != "System.Enum" &&
        typeof(T).BaseType.FullName != "System.ValueType") {
        throw new ArgumentException("Type must be of Enum and not " + typeof(T).BaseType.FullName);
    }

    if (typeof(T).BaseType.FullName == "System.ValueType")
        return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)), s, true);

    return (T)Enum.Parse(typeof(T), s, true);
}

Use like this...

Gender? g = "Female".ToEnum<Gender?>();
攒一口袋星星 2024-10-02 08:32:14

这一个完成了工作,而且看起来也很漂亮。希望有帮助!

    /// <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;
    }

https://github.com/Pangamma/PangammaUtilities-CSharp/tree/ master/src/StringExtensions

This one gets the job done and it also looks pretty. Hope it helps!

    /// <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;
    }

https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions

轮廓§ 2024-10-02 08:32:14

这就是我使用的,也许对某人有用!

public static class EnumExtension
{
    public static TEnum? ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum? @default = default)
        where TEnum : struct, Enum
    {
        TEnum? @enum;
        try { @enum = (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase); }
        catch { @enum = @default; }
        return @enum;
    }
}

this is what I using, maybe useful for someone!

public static class EnumExtension
{
    public static TEnum? ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum? @default = default)
        where TEnum : struct, Enum
    {
        TEnum? @enum;
        try { @enum = (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase); }
        catch { @enum = @default; }
        return @enum;
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文