将约束类型传递给方法
这里有一些类似的问题,但似乎没有一个能完全回答我的问题。
我想创建一个采用枚举类型的方法,并为 UI 生成 ListItems 列表。具有这样的签名的东西可以工作:
public static List<ListItem> ListItemListFromEnum(Type t)
{
...
}
但我不想接受任何类型(t必须是枚举类型) 所以我可以这样做:
public static List<ListItem> ListItemListFromEnum(Enum e)
{
Type t = e.GetType();
}
只需将正确类型的枚举传递给该方法即可。这可以很好地工作,但我真的很想采用类型参数(如我的第一个示例中所示),但强制它是枚举类型。
这可能吗?有没有办法用泛型来做到这一点? 谢谢
There a few similar questions here on SO, but none seem to quite answer my question..
I want to create a method which takes an Enum Type, and generates a List of ListItems for the UI. Something with a signature like this could work:
public static List<ListItem> ListItemListFromEnum(Type t)
{
...
}
But I would prefer not to accept any type (t must be an Enum type)
So I could do something like this:
public static List<ListItem> ListItemListFromEnum(Enum e)
{
Type t = e.GetType();
}
and just pass an enum of the correct type to the method. That would work fine, but I'd really like to take a Type parameter (as in my first example) but force it to be an Enum type.
Is this possible? Is there a way to do it with generics?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从 C# 7.3 开始,现在可以实现:
并且
T
将被限制为枚举。请注意,您必须使用类型Enum
,关键字enum
将无法编译。在 C# 的早期版本中,这是不可能的。
如果您无法使用该版本的 C#,您可以按原样接受
Type
并检查IsEnum
属性。如果是,则抛出异常。同样,您可以对泛型执行相同的操作:
唯一的缺点是您将得到运行时异常而不是编译时异常。
As of C# 7.3, this is now possible:
And
T
will be constrained to an enum. Note you must use the typeEnum
, the keywordenum
will not compile.In prior versions of C#, this is not possible.
If you cannot use that version of C#, you can just accept the
Type
as you are and check theIsEnum
property. If it is, throw an Exception.Likewise you could do the same with a generic:
The only negative there is you will get a runtime exception rather than a compile-time one.
您可以接受
Type
,然后如果该类型不是enum
类型,则抛出异常。这可能是最好的方法(直到 C# 允许泛型类型占位符受Enum
约束(如果有的话)。这就是 C# 本身对许多
Enum
类的静态方法(例如Enum.GetEnumNames()
)所做的事情。You can accept the
Type
and then throw if that type is not anenum
type. That is probably the best way (until C# allows generic type placeholders to be constrained byEnum
, if ever).This is what C# itself does with many of the
Enum
class's static methods (such asEnum.GetEnumNames()
).