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

问题描述 投票:0回答:4

这是对这个问题的阐述: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

但是那也给了我编译错误。

感谢您的帮助!

c# reflection enumerator
4个回答
1
投票
我认为这个问题可以重申为:“如何在枚举值上放置通用约束”。

Jon Skeet在这里写过博客:http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx

已问问题previously on SO


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

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

其中T的限制与CheckEnumerator的限制相同。

0
投票
不可能(在遇到相同问题时无法找到方法)将通用条件限制为Enum

更新

您能得到的最接近的是一个

ValueType struct

其中T:ValueType

where T : struct
[注意:抱歉,感谢n8wrl,它是struct

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 } } }

© www.soinside.com 2019 - 2024. All rights reserved.