这是对这个问题的阐述: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
但是那也给了我编译错误。
感谢您的帮助!
Jon Skeet在这里写过博客:http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx
已问问题previously on SO
private static void DoSomethingWithAnEnumeratorValue<T>(T item) where T : ...
{
}
其中T的限制与CheckEnumerator的限制相同。
Enum
。更新
ValueType
struct
:
其中T:ValueType
where T : struct
[注意:抱歉,感谢n8wrl,它是struct
。
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 } } }