SO 上有几个类似的问题,但似乎没有一个能完全回答我的问题..
我想创建一个采用枚举类型并为 UI 生成列表项列表的方法。带有这样签名的东西可以工作:
public static List<ListItem> ListItemListFromEnum(Type t)
{
...
}
但我宁愿不接受任何类型(t 必须是枚举类型) 所以我可以做这样的事情:
public static List<ListItem> ListItemListFromEnum(Enum e)
{
Type t = e.GetType();
}
然后将正确类型的枚举传递给方法。这样可以正常工作,但我真的很想采用 Type 参数(如我的第一个示例),但强制它成为 Enum 类型。
这可能吗?有没有办法用泛型来做到这一点? 谢谢
最佳答案
自 C# 7.3 起,this is now possible :
public static List<ListItem> ListItemsListFromEnum<T>() where T:System.Enum
T
将被限制为一个枚举。请注意,您必须使用类型 Enum
,关键字 enum
将无法编译。
在以前的 C# 版本中,这是不可能的。
如果您不能使用该版本的 C#,您可以直接接受 Type
并检查 IsEnum
属性(property)。如果是,则抛出异常。
public static List<ListItem> ListItemListFromEnum(Type t)
{
if (!t.IsEnum)
{
throw new ArgumentException("Type must be an enumeration", "t");
}
}
同样,您可以对泛型做同样的事情:
public static List<ListItem> ListItemListFromEnum<T>()
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Type must be an enumeration", "t");
}
}
唯一的缺点是你会得到运行时异常而不是编译时异常。
关于c# - 将约束类型传递给方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7903894/