将未知的枚举值传递给函数
本文关键字:函数 值传 枚举 未知 | 更新日期: 2023-09-27 18:14:09
这是对这个问题的详细说明:
我创建了一个小示例应用程序来介绍我的问题:
UPDATE:这是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
这个问题之前在SO
从c# 7.3开始,可以创建enum约束:
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
}
}
}
您还需要确保DoSomethingWithAnEnumeraterValue(item)的类型与您的T匹配:
private static void DoSomethingWithAnEnumeratorValue<T>(T item) where T : ...
{
}
其中T和CheckEnumerator一样受到限制
将通用条件限制为Enum
是不可能的(当我遇到同样的问题时,我找不到方法)。
最接近a ValueType
struct
:
where T: ValueType
where T : struct
注意:抱歉,是的,这是struct
感谢n8wrl。