如何将通用 Tryparse 与 Enum 一起使用? [英] How to use generic Tryparse with Enum?

查看:18
本文介绍了如何将通用 Tryparse 与 Enum 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建从用户字符串中获取的通用函数,并尝试将其解析为枚举值,如下所示:

I'm trying to build generic function that get from user string and try to parse it to Enum valuse like this:

private Enum getEnumStringEnumType(Type i_EnumType)
    {
        string userInputString = string.Empty;
        Enum resultInputType;
        bool enumParseResult = false;

        while (!enumParseResult)
        {                
            userInputString = System.Console.ReadLine();
            enumParseResult = Enum.TryParse(userInputString, true, out resultInputType);
        }
    }

但我明白了:

The type 'System.Enum' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'System.Enum.TryParse<TEnum>(string, bool, out TEnum)    .

错误意味着我需要为 resultInputType 声明一个特定的 Enum?我怎样才能解决这个问题 ?谢谢.

The Error means that i need to decalare a specific Enum for resultInputType? How can I fix this ? Thanks.

推荐答案

TryParse 方法具有以下签名:

The TryParse method has the following signature:

TryParse<TEnum>(string value, bool ignoreCase, out TEnum result)
    where TEnum : struct

它有一个泛型类型参数TEnum,它必须是一个struct,用于确定被解析的枚举类型.当您没有明确提供它时(如您所做的那样),它将采用您提供的任何类型作为 result 参数,在您的情况下为 Enum 类型(而不是枚举本身的类型).

It has a generic type parameter TEnum that must be a struct and that is used to determine the type of enumeration being parsed. When you don't provide it explicitly (as you did), it will take the type of whatever you provide as the result argument, which in your case is of type Enum (and not the type of the enumeration itself).

请注意,Enum 是一个 class(尽管它继承自 ValueType),因此它不满足 TEnumstruct 的要求>.

Note that Enum is a class (despite it inheriting from ValueType) and therefore it does not satisfy the requirement that TEnum is a struct.

您可以通过删除 Type 参数并为该方法提供具有与 Type 上的泛型类型参数相同约束(即 struct)的泛型类型参数来解决此问题code>TryParse 函数.

You can solve this by removing the Type parameter and giving the method a generic type parameter with the same constraints (i.e. struct) as the generic type parameter on the TryParse function.

所以试试这个,我将泛型类型参数命名为 TEnum:

So try this, where I've named the generic type parameter TEnum:

private static TEnum GetEnumStringEnumType<TEnum>()
    where TEnum : struct
{
    string userInputString = string.Empty;
    TEnum resultInputType = default(TEnum);
    bool enumParseResult = false;

    while (!enumParseResult)
    {                
        userInputString = System.Console.ReadLine();
        enumParseResult = Enum.TryParse(userInputString, true, out resultInputType);
    }
    return resultInputType;
}

要调用该方法,请使用:

To call the method, use:

GetEnumStringEnumType<MyEnum>();

这篇关于如何将通用 Tryparse 与 Enum 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆