传递枚举命令行参数
问题描述:
所以我有这个开关,以设置等待时间传递枚举命令行参数
public int Option(string arg)
{
switch (arg)
{
case "/t:Max":
return 0;
case "/t:Med":
return 1000;
case "/t:Min":
return 2000;
default: return 0;
}
}
如何使用枚举为/吨:民/吨:地中海,/t.Max以更换开关?
确实是这样的:
enum t
{
/t:Min,
/t:Med,
/t:Max
};
答
你的枚举应该是这样的:
public enum WaitTime
{
Min, Max, Med
}
和交换机转换为这样的:
switch ((WaitTime)Enum.Parse(typeof(WaitTime), arg.Replace("/:", string.Empty)))
{
case WaitTime.Max:
return 0;
case WaitTime.Med:
return 1000;
case WaitTime.Min:
return 2000;
default:
return 0;
}
+0
@abatishchev谢谢;) – 2012-08-03 09:35:58
答
,您应该使用的TryParse
Enum.Parse
。另请参阅:http://msdn.microsoft.com/en-us/library/system.enum.parse.aspx
但仍然需要从命令行参数中检索字符串(去掉'/ t:')并将其解析为Enum
。
答
代码:
enum YourEnum
{
Min,
Med,
Max
};
void Main(string[] args)
{
var arg0 = args[0]; // "/t:Min"
var arg0arr = arg0.Split(':') // { "/t", "Min" }
var arg0val = arg0arr[1]; // "Min"
var e = Enum.Parse(typeof(YourEnum), arg0val);
}
呼叫应用:
app.exe /t:Min
答
纠正我,如果我错了,但不是最简单的方法只是使用arg作为键和时间作为值的字典,并使用.TryGetValue(),如果失败只是返回0?
像这样: arguments.Add可能在构造函数中发生,dosn't不需要在方法中。
private static Dictionary<string, int> arguments = new Dictionary<string, int>(5);
public int Option(string arg)
{
arguments.Add("Max", 0);
arguments.Add("Med", 1000);
arguments.Add("Min", 2000);
int value;
if (arguments.TryGetValue(arg.Replace("/:", string.Empty), out value))
return value;
//default
return 0;
}
答
试试这个:
public enum t
{
[Description("/t:Min")] // <<---- set the string equivalent of the enum HERE.
min = 0, // <<---- set the return value of the enum HERE.
[Description("/t:Med")]
med = 1000,
[Description("/t:Max")]
max = 2000
}
您还需要这个方便的小类:
public static class EnumHelper
{
public static list_of_t = Enum.GetValues(typeof(t)).Cast<t>().ToList();
// returns the string description of the enum.
public static string GetEnumDescription(this Enum value)
{
FieldInfo fi = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes =
(DescriptionAttribute[])fi.GetCustomAttributes(
typeof(DescriptionAttribute),
false);
if (attributes.Length > 0)
return attributes[0].Description;
else
return value.ToString();
}
}
您可以使用装饰枚举这样得到你需要的东西:
public int Option(string arg)
{
// get the matching enum for the "/t:" switch here.
var foundItem =
EnumHelper.list_of_t.SingleOrDefault(c => c.GetEnumDescription() == arg);
if (foundItem != null)
{
return (int)foundItem; // <<-- this will return 0, 1000, or 2000 in this example.
}
else
{
return 0;
}
}
HTH ...
Enum.TryParse()浮现在脑海...... – 2012-08-02 13:36:15
@JamesMichaelHare:虽然它用一个枚举替换了字符串,但它不会消除对该开关的需要。除非数字是在enum常量中编码的,我可能会称其为hack :-) – 2012-08-02 13:37:30
您将不得不失去/ t:部分。 – hatchet 2012-08-02 13:38:09