これは、この質問の詳細です。c#列挙型関数パラメーター
私の質問を紹介するために、小さなサンプルアプリケーションを作成しました。
更新:これは、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
しかし、それは私にコンパイルエラーも与えています。
助けてくれてありがとう!