如何在此上下文中传递枚举 [英] How do I pass an enum in this context
本文介绍了如何在此上下文中传递枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想改变我写,这样它会枚举(在这种情况下MyColors)作为参数,这样我可以使用在任何合适的连续枚举函数下面的函数。到目前为止,我已经试过各种失败,所以我卡住了。
私人枚举MyColors {红,绿,蓝}
私人字符串的GetNext(字符串colorName)
{
MyColors colorValue;
字符串colorNameOut =的String.Empty;
如果(Enum.TryParse(colorName,出colorValue))
{
MyColors初始= colorValue,旁边= colorValue;
的for(int i =((Int32)已初步)+ 1;我小于10;我++)
{
如果(Enum.IsDefined(typeof运算(MyColors),我))
{
下一=(MyColors)我;
中断;
}
,否则
{
下一=(MyColors)0;
}
}
colorNameOut = next.ToString();
}
返回colorNameOut;
}
解决方案
下面应该工作:
私有静态字符串的GetNext< T>(字符串colorName)其中T:结构
{
// (!typeof运算(T).IsEnum)确认那件T实际上是一个枚举类型
如果
抛出新的ArgumentException(类型参数必须是一个枚举类型);
$ B $(B T)colorValue;
字符串colorNameOut =的String.Empty;
如果(Enum.TryParse< T>(colorName,出colorValue))
{$ B $(B T)=初始colorValue,旁边= colorValue;
的for(int i =(Convert.ToInt32(初始))+ 1;我小于10;我++)
{
如果(Enum.IsDefined(typeof运算(T) ,I))
{
下一=(T)Enum.ToObject(typeof运算(T),I);
中断;
}
,否则
{
下一=(T)Enum.ToObject(typeof运算(T),0);
}
}
colorNameOut = next.ToString();
}
返回colorNameOut;
}
由于该方法是目前通用的它必须用一个类型参数调用枚举类型,如:
的GetNext< MyColors>(红楼梦)
I want to change the below function that I have written so that it will take the Enum (MyColors in this instance) as argument so that I can use the function on any suitable contiguous Enum. Everything I have tried so far has failed so I'm stuck.
private enum MyColors { Red, Green, Blue }
private String GetNext(String colorName)
{
MyColors colorValue;
String colorNameOut = String.Empty;
if (Enum.TryParse(colorName, out colorValue))
{
MyColors initial = colorValue, next = colorValue;
for (int i = ((Int32)initial) + 1; i < 10; i++)
{
if (Enum.IsDefined(typeof(MyColors), i))
{
next = (MyColors)i;
break;
}
else
{
next = (MyColors)0;
}
}
colorNameOut = next.ToString();
}
return colorNameOut;
}
解决方案
The following ought to work:
private static String GetNext<T>(String colorName) where T : struct
{
// Verify that T is actually an enum type
if (!typeof(T).IsEnum)
throw new ArgumentException("Type argument must be an enum type");
T colorValue;
String colorNameOut = String.Empty;
if (Enum.TryParse<T>(colorName, out colorValue))
{
T initial = colorValue, next = colorValue;
for (int i = (Convert.ToInt32(initial)) + 1; i < 10; i++)
{
if (Enum.IsDefined(typeof(T), i))
{
next = (T)Enum.ToObject(typeof(T), i);
break;
}
else
{
next = (T)Enum.ToObject(typeof(T), 0);
}
}
colorNameOut = next.ToString();
}
return colorNameOut;
}
Since the method is now generic it has to be called with a type argument of the enum type, like:
GetNext<MyColors>("Red")
这篇关于如何在此上下文中传递枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文