c#枚举函数参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/507396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# Enum Function Parameters
提问by TK.
As a follow on from this question.
How can I call a function and pass in an Enum?
如何调用函数并传入枚举?
For example I have the following code:
例如,我有以下代码:
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!
}
}
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?
虽然当我这样做时,我得到的 'e1' 是一个 'type',但它被用作一个 'variable' 错误消息。有什么想法可以帮助吗?
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?
我试图保持函数通用以适用于任何 Enum 而不仅仅是特定类型?这甚至可能吗?...如何使用通用函数?这行得通吗?
采纳答案by bruno conde
You can use a generic function:
您可以使用通用函数:
public void myFunc<T>()
{
var names = Enum.GetNames(typeof(T));
foreach (var name in names)
{
// do something!
}
}
and call like:
并调用:
myFunc<e1>();
(EDIT)
(编辑)
The compiler complains if you try to constraint T
to Enum
or enum
.
如果您尝试约束T
到Enum
或,编译器会抱怨enum
。
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!
}
}
回答by Andrew Hare
You are trying to pass the type of the enum as an instance of that type - try something like this:
您正在尝试将枚举类型作为该类型的实例传递 - 尝试如下操作:
enum e1
{
foo, bar
}
public void test()
{
myFunc(e1.foo); // this needs to be e1.foo or e1.bar - not e1 itself
}
public void myFunc(Enum e)
{
foreach (string item in Enum.GetNames(e.GetType()))
{
// Print values
}
}
回答by Martin Moser
Why not passing the type? like:
为什么不传递类型?喜欢:
myfunc(typeof(e1));
public void myFunc( Type t )
{
}
回答by abatishchev
Use
用
public void myFunc( e1 e ) { // use enum of type e}
instead of
代替
public void myFunc( Enum e ) { // use type enum. The same as class or interface. This is not generic! }