c#中的通用枚举字符串值分析器?

c#中的通用枚举字符串值分析器?,c#,enums,enumeration,text-parsing,C#,Enums,Enumeration,Text Parsing,我有一个关于从字符串解析枚举的奇怪问题。事实上,我的应用程序需要处理配置文件中少数枚举的解析。但是,我不想为每种枚举类型编写解析例程(因为有很多) 我面临的问题是,下面的代码显示了一些奇怪的错误-T的类型必须是不可为null的值类型或类似的类型。我认为枚举在默认情况下是不可为空的 如果我使用where T:enum限制T的类型,则方法体中的所有其他内容(除了If enum.TryParse语句)都会被下划线为错误 有人能帮忙解决这个奇怪的小问题吗 谢谢, 马丁 公共静态T GetConfigEn

我有一个关于从字符串解析枚举的奇怪问题。事实上,我的应用程序需要处理配置文件中少数枚举的解析。但是,我不想为每种枚举类型编写解析例程(因为有很多)

我面临的问题是,下面的代码显示了一些奇怪的错误-T的类型必须是不可为null的值类型或类似的类型。我认为枚举在默认情况下是不可为空的

如果我使用
where T:enum
限制
T
的类型,则方法体中的所有其他内容(除了
If enum.TryParse
语句)都会被下划线为错误

有人能帮忙解决这个奇怪的小问题吗

谢谢, 马丁

公共静态T GetConfigEnumValue(NameValueCollection配置, 字符串configKey, T defaultValue)//其中T:enum? { if(config==null) { 返回默认值; } 如果(配置[configKey]==null) { 返回默认值; } T结果=默认值; 字符串configValue=config[configKey].Trim(); if(string.IsNullOrEmpty(configValue)) { 返回默认值; } //给我一个错误-T必须是不可为null的值类型? 如果(!Enum.TryParse(配置值,输出结果)) { 结果=默认值; } //给我同样的错误: //如果(!Enum.TryParse(configValue,out result))。。。 返回结果; } 用户请求发布错误文本(它是在代码时,而不是在编译/运行时),因此:

类型“T”必须是不可为null的值类型,才能将其用作泛型类型或方法“System.Enum.TryParse(string,out TEnum)”中的参数TEnum

由于C#不允许您执行
where t:enum
,因此必须使用
where t:struct


请注意,有一些方法可以绕过建议的限制。

啊,好的,记住这些信息,我知道
Enum.TryParse
方法在抱怨什么

在方法上设置常规约束,如下所示:

public static T GetConfigEnumValue<T>(NameValueCollection config, 
                                      string configKey, 
                                      T defaultValue) // where T : ValueType
您可以在此处找到此定义:

公共静态T GetConfigEnumValue(NameValueCollection配置、字符串configKey、T defaultValue)
{
if(config==null)
{
返回默认值;
}
如果(配置[configKey]==null)
{
返回默认值;
}
T结果=默认值;
字符串configValue=config[configKey].Trim();
if(string.IsNullOrEmpty(configValue))
{
返回默认值;
}
尝试
{
结果=(T)Enum.Parse(typeof(T),configValue,true);
}
抓住
{
结果=默认值;
}
返回结果;
}

您可以附加错误吗?如果没有where条件,您的代码看起来应该可以工作。@jdv Jan de Vaan这行吗?我的意思是我知道枚举是真正的整数,整数的类型是System.Int32结构。。。但是它真的有效吗?看看,它可能会有帮助。@bleep:枚举可以从任何整数类型(
byte
long
,等等)派生出来。@bleepzter:现在您添加了错误消息,我确认这是解决方案。所以回想起来,我应该把它作为一个答案发布。请注意,
其中T:ValueType
不起作用,
ValueType
可以为空,它必须是一个
其中T:struct
public static T GetConfigEnumValue<T>(NameValueCollection config, 
                                      string configKey, 
                                      T defaultValue) // where T : ValueType
where T : struct, new()
public static T GetConfigEnumValue<T>(NameValueCollection config, string configKey, T defaultValue)
{
    if (config == null)
    {
        return defaultValue;
    }

    if (config[configKey] == null)
    {
        return defaultValue;
    }

    T result = defaultValue;
    string configValue = config[configKey].Trim();

    if (string.IsNullOrEmpty(configValue))
    {
        return defaultValue;
    }

    try
    {
        result = (T)Enum.Parse(typeof(T), configValue, true);
    }
    catch
    {
        result = defaultValue;
    }

    return result;
}