简体   繁体   English

为Nullable Enum添加约束

[英]Adding Constraints for Nullable Enum

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

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. 我现在想要将T的约束添加到Enum,例如(我从Stackoverflow文章中得到): where T : struct, IConvertible但我遇到问题,因为T需要能够获取可以为空的枚举。 Error message says: 错误消息说:

The type 'Enums.Animals?' 类型'Enums.Animals?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 必须是非可空值类型才能在泛型类型或方法中将其用作参数“T”

Is there a way to do this, or do I need to just rely on the runtime checking which I have inside the method? 有没有办法做到这一点,或者我需要依靠运行时检查我在方法内部?

Thanks all! 谢谢大家!

No, there's no constraint which says "T must be a value type, including nullable value types." 不,没有约束说“T必须是值类型,包括可以为值的值类型”。

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. 当然,我们不知道您将如何使用此代码 - 但如果您要直接从非泛型方法调用它,这将是我建议的方法。

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. 当然,这仍然不会阻止某人用T=int或类似的东西来调用它......你可能想要看看Unconstrained Melody更严格的约束。

There is a trick that involves C++/CLI which does allow generic constraints on Enums. 有一个涉及C ++ / CLI的技巧,它允许对Enums进行通用约束。 Write a base abstract class in C++/CLI with the Enum constraint. 使用Enum约束在C ++ / CLI中编写基本抽象类。 Reference the library in a C# project and implement the base class. 在C#项目中引用库并实现基类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM