首页 文章

创建将T限制为枚举的通用方法

提问于
浏览
992

我正在构建一个扩展 Enum.Parse 概念的函数

  • 允许在未找到枚举值的情况下解析默认值

  • 不区分大小写

所以我写了以下内容:

public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
    if (string.IsNullOrEmpty(value)) return defaultValue;
    foreach (T item in Enum.GetValues(typeof(T)))
    {
        if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
    }
    return defaultValue;
}

我得到一个错误约束不能是特殊类 System.Enum .

不够公平,但有一种变通方法,让一个通用枚举,还是我将不得不模仿 Parse 功能,并通过一个类型的属性,这迫使丑拳击要求你的代码 .

EDIT 以下所有建议都非常感谢,谢谢 .

已经解决了(我已经离开循环以保持不区分大小写 - 我在解析XML时使用它)

public static class EnumUtils
{
    public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
        if (string.IsNullOrEmpty(value)) return defaultValue;

        foreach (T item in Enum.GetValues(typeof(T)))
        {
            if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
        }
        return defaultValue;
    }
}

EDIT: (2015年2月16日)Julien Lebosquain最近发布了下面的a compiler enforced type-safe generic solution in MSIL or F#,这是非常值得一看的,也是一个upvote . 如果解决方案在页面上向上冒泡,我将删除此编辑 .

20 回答

  • 1

    我通过dimarzionist修改了样本 . 此版本仅适用于Enums,不允许结构通过 .

    public static T ParseEnum<T>(string enumString)
        where T : struct // enum 
        {
        if (String.IsNullOrEmpty(enumString) || !typeof(T).IsEnum)
           throw new Exception("Type given must be an Enum");
        try
        {
    
           return (T)Enum.Parse(typeof(T), enumString, true);
        }
        catch (Exception ex)
        {
           return default(T);
        }
    }
    
  • 29

    C#≥7.3

    从C#7.3开始(Visual Studio2017≥v15.7提供),此代码现在完全有效:

    public static TEnum Parse<TEnum>(string value)
    where TEnum : struct, Enum { ... }
    

    C#≤7.2

    您可以通过滥用约束继承来获得真正的编译器强制枚举约束 . 以下代码同时指定了 classstruct 约束:

    public abstract class EnumClassUtils<TClass>
    where TClass : class
    {
    
        public static TEnum Parse<TEnum>(string value)
        where TEnum : struct, TClass
        {
            return (TEnum) Enum.Parse(typeof(TEnum), value);
        }
    
    }
    
    public class EnumUtils : EnumClassUtils<Enum>
    {
    }
    

    用法:

    EnumUtils.Parse<SomeEnum>("value");
    

    注意:这在C#5.0语言规范中有明确说明:

    如果类型参数S取决于类型参数T则:[...] S对于具有值类型约束而T具有引用类型约束是有效的 . 实际上,这将T限制为System.Object,System.ValueType,System.Enum和任何接口类型 .

  • 1

    我已将Vivek的解决方案封装到您可以重用的实用程序类中 . 请注意,您仍应在类型上定义类型约束“where T:struct,IConvertible” .

    using System;
    
    internal static class EnumEnforcer
    {
        /// <summary>
        /// Makes sure that generic input parameter is of an enumerated type.
        /// </summary>
        /// <typeparam name="T">Type that should be checked.</typeparam>
        /// <param name="typeParameterName">Name of the type parameter.</param>
        /// <param name="methodName">Name of the method which accepted the parameter.</param>
        public static void EnforceIsEnum<T>(string typeParameterName, string methodName)
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
            {
                string message = string.Format(
                    "Generic parameter {0} in {1} method forces an enumerated type. Make sure your type parameter {0} is an enum.",
                    typeParameterName,
                    methodName);
    
                throw new ArgumentException(message);
            }
        }
    
        /// <summary>
        /// Makes sure that generic input parameter is of an enumerated type.
        /// </summary>
        /// <typeparam name="T">Type that should be checked.</typeparam>
        /// <param name="typeParameterName">Name of the type parameter.</param>
        /// <param name="methodName">Name of the method which accepted the parameter.</param>
        /// <param name="inputParameterName">Name of the input parameter of this page.</param>
        public static void EnforceIsEnum<T>(string typeParameterName, string methodName, string inputParameterName)
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
            {
                string message = string.Format(
                    "Generic parameter {0} in {1} method forces an enumerated type. Make sure your input parameter {2} is of correct type.",
                    typeParameterName,
                    methodName,
                    inputParameterName);
    
                throw new ArgumentException(message);
            }
        }
    
        /// <summary>
        /// Makes sure that generic input parameter is of an enumerated type.
        /// </summary>
        /// <typeparam name="T">Type that should be checked.</typeparam>
        /// <param name="exceptionMessage">Message to show in case T is not an enum.</param>
        public static void EnforceIsEnum<T>(string exceptionMessage)
            where T : struct, IConvertible
        {
            if (!typeof(T).IsEnum)
            {
                throw new ArgumentException(exceptionMessage);
            }
        }
    }
    
  • 18

    我确实有特定的要求,我需要使用enum与enum值相关联的文本 . 例如,当我使用enum指定错误类型时,它需要描述错误详细信息 .

    public static class XmlEnumExtension
    {
        public static string ReadXmlEnumAttribute(this Enum value)
        {
            if (value == null) throw new ArgumentNullException("value");
            var attribs = (XmlEnumAttribute[]) value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (XmlEnumAttribute), true);
            return attribs.Length > 0 ? attribs[0].Name : value.ToString();
        }
    
        public static T ParseXmlEnumAttribute<T>(this string str)
        {
            foreach (T item in Enum.GetValues(typeof(T)))
            {
                var attribs = (XmlEnumAttribute[])item.GetType().GetField(item.ToString()).GetCustomAttributes(typeof(XmlEnumAttribute), true);
                if(attribs.Length > 0 && attribs[0].Name.Equals(str)) return item;
            }
            return (T)Enum.Parse(typeof(T), str, true);
        }
    }
    
    public enum MyEnum
    {
        [XmlEnum("First Value")]
        One,
        [XmlEnum("Second Value")]
        Two,
        Three
    }
    
     static void Main()
     {
        // Parsing from XmlEnum attribute
        var str = "Second Value";
        var me = str.ParseXmlEnumAttribute<MyEnum>();
        System.Console.WriteLine(me.ReadXmlEnumAttribute());
        // Parsing without XmlEnum
        str = "Three";
        me = str.ParseXmlEnumAttribute<MyEnum>();
        System.Console.WriteLine(me.ReadXmlEnumAttribute());
        me = MyEnum.One;
        System.Console.WriteLine(me.ReadXmlEnumAttribute());
    }
    
  • 11

    希望这有用:

    public static TValue ParseEnum<TValue>(string value, TValue defaultValue)
                      where TValue : struct // enum 
    {
          try
          {
                if (String.IsNullOrEmpty(value))
                      return defaultValue;
                return (TValue)Enum.Parse(typeof (TValue), value);
          }
          catch(Exception ex)
          {
                return defaultValue;
          }
    }
    
  • 3

    在java中,你会用...

    SomeClass<T extends enum> {
    }
    

    很简单,那个 .

  • -4

    这是我的看法 . 结合答案和MSDN

    public static TEnum ParseToEnum<TEnum>(this string text) where TEnum : struct, IConvertible, IComparable, IFormattable
    {
        if (string.IsNullOrEmpty(text) || !typeof(TEnum).IsEnum)
            throw new ArgumentException("TEnum must be an Enum type");
    
        try
        {
            var enumValue = (TEnum)Enum.Parse(typeof(TEnum), text.Trim(), true);
            return enumValue;
        }
        catch (Exception)
        {
            throw new ArgumentException(string.Format("{0} is not a member of the {1} enumeration.", text, typeof(TEnum).Name));
        }
    }
    

    MSDN Source

  • 1

    您可以为类定义静态构造函数,该构造函数将检查类型T是否为枚举,如果不是则抛出异常 . 这是Jeffery Richter在他的书CLR中通过C#提到的方法 .

    internal sealed class GenericTypeThatRequiresAnEnum<T> {
        static GenericTypeThatRequiresAnEnum() {
            if (!typeof(T).IsEnum) {
            throw new ArgumentException("T must be an enumerated type");
            }
        }
    }
    

    然后在parse方法中,您可以使用Enum.Parse(typeof(T),input,true)将字符串转换为枚举 . 最后一个真实参数用于忽略输入的大小写 .

  • 161

    我创建了一个扩展方法 to get integer value from enum 看看方法实现

    public static int ToInt<T>(this T soure) where T : IConvertible//enum
    {
        if (typeof(T).IsEnum)
        {
            return (int) (IConvertible)soure;// the tricky part
        }
        //else
        //    throw new ArgumentException("T must be an enumerated type");
        return soure.ToInt32(CultureInfo.CurrentCulture);
    }
    

    这是用法

    MemberStatusEnum.Activated.ToInt()// using extension Method
    (int) MemberStatusEnum.Activated //the ordinary way
    
  • 467

    从C#<= 7.2开始,现有答案都是正确的 . 但是,有一个C#语言feature request(与corefx功能请求绑定)允许以下内容;

    public class MyGeneric<TEnum> where TEnum : System.Enum
    { }
    

    在撰写本文时,该功能在语言发展 Session 上进行了“讨论” .

    EDIT

    根据nawfal的信息,这是在C#7.3中引入的 .

  • 3

    还应该考虑到,因为使用Enum约束的C#7.3的发布支持开箱即用而无需进行额外的检查和填充 .

    因此,如果您已将项目的语言版本更改为C#7.3,则以下代码将完美地运行:

    private static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
        {
            // Your code goes here...
        }
    

    如果您知道如何将语言版本更改为C#7.3,请参阅以下屏幕截图:

    EDIT 1 - Required Visual Studio Version and considering ReSharper

    要使Visual Studio能够识别至少需要15.7版本的新语法 . 您可以找到Microsoft发行说明中提到的内容,请参阅Visual Studio 2017 15.7 Release Notes . 感谢@MohamedElshawaf指出这个有效的问题 .

    请注意,在我的案例中,ReSharper 2018.1在编写此EDIT时尚不支持C#7.3 . 有ReSharper的激活它突出的枚举约束为一个错误,告诉我不能用'System.Array','System.Delegate','System.Enum','System.ValueType','object'类型参数约束 . ReSharper建议快速修复删除方法类型参数T的'Enum'约束

    但是,如果您在工具暂时关闭ReSharper的 - >选项 - > ReSharper的终极 - >常规,你会看到,语法是完全没有考虑到你使用VS 15.7或更高版本和C#7.3或更高版本 .

  • 1

    有趣的是,显然这是possible in other langauges(Managed C,IL直接) .

    报价:

    ...两个约束实际上产生有效的IL,如果用另一种语言编写,也可以被C#使用(您可以在托管C或IL中声明这些约束) .

    谁知道

  • 3

    我喜欢使用IL的Christopher Currens解决方案,但对于那些不想处理将MSIL包含在构建过程中的棘手业务的人,我在C#中编写了类似的功能 .

    请注意,虽然您不能使用像 where T : Enum 这样的通用限制,因为Enum是特殊类型 . 因此,我必须检查给定的泛型类型是否真的是枚举 .

    我的功能是:

    public static T GetEnumFromString<T>(string strValue, T defaultValue)
    {
        // Check if it realy enum at runtime 
        if (!typeof(T).IsEnum)
            throw new ArgumentException("Method GetEnumFromString can be used with enums only");
    
        if (!string.IsNullOrEmpty(strValue))
        {
            IEnumerator enumerator = Enum.GetValues(typeof(T)).GetEnumerator();
            while (enumerator.MoveNext())
            {
                T temp = (T)enumerator.Current;
                if (temp.ToString().ToLower().Equals(strValue.Trim().ToLower()))
                    return temp;
            }
        }
    
        return defaultValue;
    }
    
  • 5

    如果以后可以直接使用直接投射,我猜你可以在你的方法中使用 System.Enum 基类,只要有必要 . 您只需要仔细更换类型参数 . 所以方法实现如下:

    public static class EnumUtils
    {
        public static Enum GetEnumFromString(string value, Enum defaultValue)
        {
            if (string.IsNullOrEmpty(value)) return defaultValue;
            foreach (Enum item in Enum.GetValues(defaultValue.GetType()))
            {
                if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
            }
            return defaultValue;
        }
    }
    

    然后你可以使用它喜欢:

    var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);
    
  • 1

    我总是喜欢这个(你可以适当修改):

    public static IEnumerable<TEnum> GetEnumValues()
    {
      Type enumType = typeof(TEnum);
    
      if(!enumType.IsEnum)
        throw new ArgumentException("Type argument must be Enum type");
    
      Array enumValues = Enum.GetValues(enumType);
      return enumValues.Cast<TEnum>();
    }
    
  • 899

    由于 Enum Type实现了 IConvertible 接口,更好的实现应该是这样的:

    public T GetEnumFromString<T>(string value) where T : struct, IConvertible
    {
       if (!typeof(T).IsEnum) 
       {
          throw new ArgumentException("T must be an enumerated type");
       }
    
       //...
    }
    

    这仍然允许传递实现 IConvertible 的值类型 . 但机会很少 .

  • 9

    我试着改进一下代码:

    public T LoadEnum<T>(string value, T defaultValue = default(T)) where T : struct, IComparable, IFormattable, IConvertible
    {
        if (Enum.IsDefined(typeof(T), value))
        {
            return (T)Enum.Parse(typeof(T), value, true);
        }
        return defaultValue;
    }
    
  • 9

    Edit

    Julien Lebosquain现在已经很好地回答了这个问题 . 我还想用 ignoreCasedefaultValue 和可选参数扩展他的答案,同时添加 TryParseParseOrDefault .

    public abstract class ConstrainedEnumParser<TClass> where TClass : class
    // value type constraint S ("TEnum") depends on reference type T ("TClass") [and on struct]
    {
        // internal constructor, to prevent this class from being inherited outside this code
        internal ConstrainedEnumParser() {}
        // Parse using pragmatic/adhoc hard cast:
        //  - struct + class = enum
        //  - 'guaranteed' call from derived <System.Enum>-constrained type EnumUtils
        public static TEnum Parse<TEnum>(string value, bool ignoreCase = false) where TEnum : struct, TClass
        {
            return (TEnum)Enum.Parse(typeof(TEnum), value, ignoreCase);
        }
        public static bool TryParse<TEnum>(string value, out TEnum result, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T
        {
            var didParse = Enum.TryParse(value, ignoreCase, out result);
            if (didParse == false)
            {
                result = defaultValue;
            }
            return didParse;
        }
        public static TEnum ParseOrDefault<TEnum>(string value, bool ignoreCase = false, TEnum defaultValue = default(TEnum)) where TEnum : struct, TClass // value type constraint S depending on T
        {
            if (string.IsNullOrEmpty(value)) { return defaultValue; }
            TEnum result;
            if (Enum.TryParse(value, ignoreCase, out result)) { return result; }
            return defaultValue;
        }
    }
    
    public class EnumUtils: ConstrainedEnumParser<System.Enum>
    // reference type constraint to any <System.Enum>
    {
        // call to parse will then contain constraint to specific <System.Enum>-class
    }
    

    用法示例:

    WeekDay parsedDayOrArgumentException = EnumUtils.Parse<WeekDay>("monday", ignoreCase:true);
    WeekDay parsedDayOrDefault;
    bool didParse = EnumUtils.TryParse<WeekDay>("clubs", out parsedDayOrDefault, ignoreCase:true);
    parsedDayOrDefault = EnumUtils.ParseOrDefault<WeekDay>("friday", ignoreCase:true, defaultValue:WeekDay.Sunday);
    

    Old

    通过使用注释和'new'开发我对Vivek's answer的旧改进:

    • 使用 TEnum 以明确用户

    • 为附加约束检查添加更多接口约束

    • TryParse使用现有参数处理 ignoreCase (在VS2010 / .Net 4中引入)

    • 可选择使用泛型default value(在VS2005 / .Net 2中引入)

    • 使用optional arguments(在VS2010 / .Net 4中引入),默认值为 defaultValueignoreCase

    导致:

    public static class EnumUtils
    {
        public static TEnum ParseEnum<TEnum>(this string value,
                                             bool ignoreCase = true,
                                             TEnum defaultValue = default(TEnum))
            where TEnum : struct,  IComparable, IFormattable, IConvertible
        {
            if ( ! typeof(TEnum).IsEnum) { throw new ArgumentException("TEnum must be an enumerated type"); }
            if (string.IsNullOrEmpty(value)) { return defaultValue; }
            TEnum lResult;
            if (Enum.TryParse(value, ignoreCase, out lResult)) { return lResult; }
            return defaultValue;
        }
    }
    
  • 4

    C#7.3最终支持此功能!

    以下代码段(来自the dotnet samples)演示了它的用途:

    public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
    {
        var result = new Dictionary<int, string>();
        var values = Enum.GetValues(typeof(T));
    
        foreach (int item in values)
            result.Add(item, Enum.GetName(typeof(T), item));
        return result;
    }
    

    请务必在C#项目中将语言版本设置为7.3版 .


    原始答案如下:

    我在C#(或VB.NET,但向下滚动F#)中是不可能的,但在MSIL中是可能的 . 我写了这个小东西

    // license: http://www.apache.org/licenses/LICENSE-2.0.html
    .assembly MyThing{}
    .class public abstract sealed MyThing.Thing
           extends [mscorlib]System.Object
    {
      .method public static !!T  GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
                                                                                              !!T defaultValue) cil managed
      {
        .maxstack  2
        .locals init ([0] !!T temp,
                      [1] !!T return_value,
                      [2] class [mscorlib]System.Collections.IEnumerator enumerator,
                      [3] class [mscorlib]System.IDisposable disposer)
        // if(string.IsNullOrEmpty(strValue)) return defaultValue;
        ldarg strValue
        call bool [mscorlib]System.String::IsNullOrEmpty(string)
        brfalse.s HASVALUE
        br RETURNDEF         // return default it empty
    
        // foreach (T item in Enum.GetValues(typeof(T)))
      HASVALUE:
        // Enum.GetValues.GetEnumerator()
        ldtoken !!T
        call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
        call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
        callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator() 
        stloc enumerator
        .try
        {
          CONDITION:
            ldloc enumerator
            callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
            brfalse.s LEAVE
    
          STATEMENTS:
            // T item = (T)Enumerator.Current
            ldloc enumerator
            callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
            unbox.any !!T
            stloc temp
            ldloca.s temp
            constrained. !!T
    
            // if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
            callvirt instance string [mscorlib]System.Object::ToString()
            callvirt instance string [mscorlib]System.String::ToLower()
            ldarg strValue
            callvirt instance string [mscorlib]System.String::Trim()
            callvirt instance string [mscorlib]System.String::ToLower()
            callvirt instance bool [mscorlib]System.String::Equals(string)
            brfalse.s CONDITION
            ldloc temp
            stloc return_value
            leave.s RETURNVAL
    
          LEAVE:
            leave.s RETURNDEF
        }
        finally
        {
            // ArrayList's Enumerator may or may not inherit from IDisposable
            ldloc enumerator
            isinst [mscorlib]System.IDisposable
            stloc.s disposer
            ldloc.s disposer
            ldnull
            ceq
            brtrue.s LEAVEFINALLY
            ldloc.s disposer
            callvirt instance void [mscorlib]System.IDisposable::Dispose()
          LEAVEFINALLY:
            endfinally
        }
    
      RETURNDEF:
        ldarg defaultValue
        stloc return_value
    
      RETURNVAL:
        ldloc return_value
        ret
      }
    }
    

    如果它是有效的C#,它会生成 would 看起来像这样的函数:

    T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
    

    然后使用以下C#代码:

    using MyThing;
    // stuff...
    private enum MyEnum { Yes, No, Okay }
    static void Main(string[] args)
    {
        Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
        Thing.GetEnumFromString("Invalid", MyEnum.Okay);  // returns MyEnum.Okay
        Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
    }
    

    不幸的是,这意味着将这部分代码用MSIL而不是C#编写,唯一的好处是你能够通过 System.Enum 约束这个方法 . 它意味着你必须以这种方式部署它 .

    删除行 .assembly MyThing{} 并按如下方式调用ilasm:

    ilasm.exe /DLL /OUTPUT=MyThing.netmodule
    

    你得到一个netmodule而不是一个程序集 .

    不幸的是,VS2010(显然更早)不支持添加netmodule引用,这意味着你需要重新调试 . 将它们作为程序集的一部分添加的唯一方法是使用 /addmodule:{files} 命令行参数自行运行csc.exe . 它在MSBuild脚本中不会太痛苦 . 当然,如果你是勇敢或愚蠢的,你可以每次手动运行csc . 当多个程序集需要访问它时,它肯定会变得更加复杂 .

    所以,它可以在.Net中完成 . 是否值得付出额外的努力?嗯,好吧,我想我会让你决定那一个 .


    F#解决方案作为替代方案

    额外信用:事实证明除了MSIL之外,至少还有一种其他.NET语言可以对 enum 进行通用限制:F# .

    type MyThing =
        static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
            /// protect for null (only required in interop with C#)
            let str = if isNull str then String.Empty else str
    
            Enum.GetValues(typedefof<'T>)
            |> Seq.cast<_>
            |> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
            |> function Some x -> x | None -> defaultValue
    

    这个更容易维护,因为它是一个完全支持Visual Studio IDE的着名语言,但您仍然需要在解决方案中使用单独的项目 . 但是,它自然会产生相当不同的IL(代码非常不同),它依赖于 FSharp.Core 库,就像任何其他外部库一样,它需要成为您的发行版的一部分 .

    以下是如何使用它(基本上与MSIL解决方案相同),并显示它在其他同义结构上正确失败:

    // works, result is inferred to have type StringComparison
    var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
    // type restriction is recognized by C#, this fails at compile time
    var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
    
  • 0

    如之前的其他答案所述;虽然这不能用源代码表示,但它实际上可以在IL Level上完成 . @Christopher Currens answer展示了IL如何做到这一点 .

    使用Fody的加载项ExtraConstraints.Fody,有一种非常简单的方法,完成构建工具,以实现这一目标 . 只需将他们的nuget包( FodyExtraConstraints.Fody )添加到您的项目中并添加如下约束(摘自ExtraConstraints自述文件):

    public void MethodWithEnumConstraint<[EnumConstraint] T>() {...}
    
    public void MethodWithTypeEnumConstraint<[EnumConstraint(typeof(ConsoleColor))] T>() {...}
    

    并且Fody将为存在的约束添加必要的IL . 另请注意约束代表的附加功能:

    public void MethodWithDelegateConstraint<[DelegateConstraint] T> ()
    {...}
    
    public void MethodWithTypeDelegateConstraint<[DelegateConstraint(typeof(Func<int>))] T> ()
    {...}
    

    关于Enums,您可能还想注意非常有趣的Enums.NET .

相关问题