将未知的枚举值传递给函数

时间:2011-11-10 14:49:09

标签: c# reflection enumerator

这是对这个问题的详细说明:c# Enum Function Parameters

我创建了一个小示例应用程序来介绍我的问题:

更新:这是C#编程语言的一个已知难点。我在代码中为在搜索引擎中找到它的人添加了使用过的解决方法。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace FlexibleEnums
{
    class Program
    {
        public enum Color
        {
            Blue,
            Red,
            Green
        };

        static void Main(string[] args)
        {
            CheckEnum<Color>();
            Console.ReadKey();
        }

        private static void CheckEnum<T>()
        {
            foreach (T item in Enum.GetValues(typeof(T)))
            {
                Console.WriteLine(item);

                // And here is the question:
                // I would like to uncheck this line, but that does not compile!
                //DoSomethingWithAnEnumValue(item);

                // Solution:
                // Not so nice, but it works.
                // (In the real program I also check for null off cource!)
                DoSomethingWithAnEnumValue(item as Enum);


            }

        }

        private static void DoSomethingWithAnEnumValue(Enum e)
        {
            Console.WriteLine(e);
        }

    }
}

我认为我应该做的事情如下:

private static void CheckEnum<T>() where T : Enum

但这也给了我编译错误。

感谢您的帮助!

4 个答案:

答案 0 :(得分:1)

我认为这个问题可以重述为“如何在枚举值上放置通用约束”。

Jon Skeet在此发表了博文:http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx

问题已被提出previously on SO

答案 1 :(得分:0)

将一般条件限制为Enum是不可能的(当我遇到同样的问题时我找不到办法)。

已更新

最接近的是 ValueType struct

其中T:ValueType

where T : struct

注意:道歉,是的,由于n8wrl,它是struct

答案 2 :(得分:0)

您还需要确保键入DoSomethingWithAnEnumeraterValue(item)以匹配您的T:

private static void DoSomethingWithAnEnumeratorValue<T>(T item) where T : ...
{
}

其中T受限于CheckEnumerator。

答案 3 :(得分:0)

自C#7.3起,就可以创建枚举约束:Enum constraints

public sealed class MyClass<T> : MyBaseClass, IMyInterface<T> where T : Enum
{
        public MyClass(Args args)
            : base(args)
        {
        }
}

我需要使用者传入几个枚举之一,该枚举必须存在于特定的命名空间中。如果使用其他枚举,我会抛出运行时异常:

public sealed class MyClass<T> : MyBaseClass, IMyInterface<T> where T : Enum
{
        public MyClass(Args args)
            : base(args)
        {
            var t = typeof(T);
            if (t.Namespace.IsNotContaining("My.Namespace.Of.Interest"))
            {
#pragma warning disable CA1303 // Do not pass literals as localized parameters
                throw new InvalidEnumArgumentException("The enum provided was not of the expected type.");
#pragma warning restore CA1303 // Do not pass literals as localized parameters
            }
        }
}

相关问题