如何在Enum中使用通用Tryparse? [英] How to use generic Tryparse with Enum?

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

问题描述

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

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 自变量,在您的情况下为枚举(而不是枚举本身的类型)。

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).

请注意, 枚举 (尽管它继承自 ValueType ),因此它不能满足 TEnum struct的要求

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 参数并为该方法提供通用类型参数来解决此问题具有与 TryParse 函数上的泛型类型参数相同的约束(即 struct )。

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>();

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

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