我需要确定一个给定类型是否为枚举类型的泛型列表。
我想到了以下代码:
void Main()
{
TestIfListOfEnum(typeof(int));
TestIfListOfEnum(typeof(DayOfWeek[]));
TestIfListOfEnum(typeof(List<int>));
TestIfListOfEnum(typeof(List<DayOfWeek>));
TestIfListOfEnum(typeof(List<DayOfWeek>));
TestIfListOfEnum(typeof(IEnumerable<DayOfWeek>));
}
void TestIfListOfEnum(Type type)
{
Console.WriteLine("Object Type: \"{0}\", List of Enum: {1}", type, IsListOfEnum(type));
}
bool IsListOfEnum(Type type)
{
var itemInfo = type.GetProperty("Item");
return (itemInfo != null) ? itemInfo.PropertyType.IsEnum : false;
}
以下是上述代码的输出结果:
Object Type: "System.Int32", List of Enum: False
Object Type: "System.DayOfWeek[]", List of Enum: False
Object Type: "System.Collections.Generic.List`1[System.Int32]", List of Enum: False
Object Type: "System.Collections.Generic.List`1[System.DayOfWeek]", List of Enum: True
Object Type: "System.Collections.Generic.List`1[System.DayOfWeek]", List of Enum: True
Object Type: "System.Collections.Generic.IEnumerable`1[System.DayOfWeek]", List of Enum: False
除了最后一个示例,所有输出都是我想要的。 它无法检测到typeof(IEnumerable<DayOfWeek>)
是枚举类型的集合。
有人知道如何在这个最后的示例中检测枚举类型吗?
IEnumerable<T>
是一个序列。ICollection<T>
是一个集合。IList<T>
是一个列表。这可能是吹毛求疵,但它与你的问题相关。 - Lucas Trzesniewski