c#枚举功能参数 [英] c# Enum Function Parameters
本文介绍了c#枚举功能参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如下此问题。
如何调用函数并传入枚举?
How can I call a function and pass in an Enum?
例如我有以下代码:
enum e1
{
//...
}
public void test()
{
myFunc( e1 );
}
public void myFunc( Enum e )
{
var names = Enum.GetNames(e.GetType());
foreach (var name in names)
{
// do something!
}
}
尽管我这样做获取'e1'是一个'类型',但是被用作'变量'错误消息。任何想法可以帮助?
Although when I do this I am getting the 'e1' is a 'type' but is used like a 'variable' Error message. Any ideas to help?
我正在努力使函数通用工作在任何枚举不仅仅是一个特定的类型?这是甚么可能吗?...如何使用通用功能?这个工作吗?
I am trying to keep the function generic to work on any Enum not just a specific type? Is this even possible?... How about using a generic function? would this work?
推荐答案
您可以使用通用函数:
public void myFunc<T>()
{
var names = Enum.GetNames(typeof(T));
foreach (var name in names)
{
// do something!
}
}
并调用:
myFunc<e1>();
(EDIT)
如果您尝试约束 T
到枚举
或枚举
。
所以,为了确保类型安全,您可以将您的功能更改为:
So, to ensure type safety, you can change your function to:
public static void myFunc<T>()
{
Type t = typeof(T);
if (!t.IsEnum)
throw new InvalidOperationException("Type is not Enum");
var names = Enum.GetNames(t);
foreach (var name in names)
{
// do something!
}
}
这篇关于c#枚举功能参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文