添加约束为空的枚举 [英] Adding Constraints for Nullable Enum

查看:250
本文介绍了添加约束为空的枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一些枚举功能,并有以下几点:

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

public static T ConvertStringToEnumValue<T>(string valueToConvert, bool isCaseSensitive)
{
    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 (String.IsNullOrWhiteSpace(valueToConvert))
      return (T)typeof(T).TypeInitializer.Invoke(null);

    valueToConvert = valueToConvert.Replace(" ", "");              

    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 call it like this:

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



我现在想添加约束到T到一个枚举,如(这是我从<一个得到HREF =http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum>文章#1 ):其中T:结构,IConvertible ,但为T需要能够把可空枚举我有问题。错误消息说:

I now want to add constraints to T to an Enum, such as (which I got from Stackoverflow article): where T : struct, IConvertible but I am having problems as T needs to be able to take nullable enums. Error message says:

该型'Enums.Animals?必须是一个非空的值类型为使用它作为参数 T'中的泛型类型或方法

The type 'Enums.Animals?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

有没有办法做到这一点,或者我需要仅仅依靠运行时检查我有方法内?

Is there a way to do this, or do I need to just rely on the runtime checking which I have inside the method?

谢谢大家!

推荐答案

T必须是值类型,包括空值类型没有,没有约束它说

No, there's no constraint which says "T must be a value type, including nullable value types."

一个选项,但是,这是该方法分为到:

One option, however, would be to split the method into to:

public static T ConvertStringToEnumValue<T>(...) where T : struct
public static T? ConvertStringToNullableEnumValue<T>(...) where T : struct



除了别的,每个方法的实现然后会更简单,太

Aside from anything else, each method's implementation would then be simpler, too.

当然,我们不知道你将如何使用此代码 - 但如果你要叫它直接从非泛型方法的,这将是我建议的方法。

Of course, we don't know how you're going to use this code - but if you're going to call it directly from non-generic methods, this would be my suggested approach.

当然,这仍然不会从<调用它阻止别人code> T = INT 或类似的东西...你可能想要看的无约束旋律了解刚性约束。

Of course, that's still not going to stop someone from calling it with T=int or something like that... you might want to look at Unconstrained Melody for more rigid constraints.

这篇关于添加约束为空的枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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