我有以下代码:
public object[] Dispatch(string arg)
{
int time;
int i = 0;
object[] array = new object[10];
if (int.Parse(arg) >= 0 && int.Parse(arg) <= 20)
{
array[i] = new ComputeParam(int.Parse(arg));
}
else
{
if (arg[0] == '/' && arg[1] == 't')
{
Options opt = new Options();
time = opt.Option(arg);
}
}
return array;
}
我将参数传递给我的程序,ArgsParser
如果它们是数字则将它们放入数组中,或者如果参数类似于/t:=Max
则设置延迟时间。
问题是我需要数组和时间,我不能返回两个值。我怎样才能解决这个问题?
答案 0 :(得分:9)
您可以使用返回类,只需创建一个自定义对象:
public class DataRC {
public object[] aObj { get; set;}
public DateTime dtTime {get; set;}
}
并更改你的功能,所以:
public class ArgsParser
{
public DataRC Dispatch(string arg)
{
DataRC dResult = new DataRC();
int time;
int i = 0;
dResult.aObj = new object[10];
if (int.Parse(arg) >= 0 && int.Parse(arg) <= 20)
{
dResult.aObj[i] = new ComputeParam(int.Parse(arg));
}
else
{
if (arg[0] == '/' && arg[1] == 't')
{
Options opt = new Options();
// Is this where you need the time?
dResult.dtTime = opt.Option(arg);
}
}
return dResult;
}
}
}
答案 1 :(得分:3)
使用c sharp out参数返回时间。这将允许您从函数返回多个值。方法参数上的out方法参数关键字使方法引用传递给方法的同一变量。当控制传递回调用方法时,对方法中的参数所做的任何更改都将反映在该变量中。
http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.71).aspx
答案 2 :(得分:2)
只要未指定.net框架,就可以在较新的框架版本上使用Tuple类型:
Tuple<object[], DateTime> Dispatch(string arg)
但正如Shai写的那样,最好为此创建一个返回类。
答案 3 :(得分:1)
你可以:
我更喜欢方法2,因为返回参数可能会变得混乱,如果调用代码将自定义对象返回到预期的状态,则调用代码会更加清晰。但当然这取决于每种情况。
答案 4 :(得分:1)
Parse()
会崩溃!使用TryParse()
arg
等于/t:=Max
或任何其他非整数,则int.Parse(arg)
会抛出exception。int.Parse()
(甚至更多!)。因此,您应该将if-else
更改为:
...
int argInt;
if(int.TryParse(arg, out argInt) && ...)
{
array[i] = new ComputeParam(argInt);
}
else
...
out
参数将方法定义更改为以下内容,并像您一样设置time
:
public object[] Dispatch(string arg, out int time)
定义如下所示的类,并返回它的实例:
class DispatchReturn
{
object[] array;
int time;
}
然后返回:
public DispatchReturn Dispatch(string arg)
您可以将array
和time
放在解析器中作为字段,但避免它!它违反了 separation of concerns 。
public ComputeParam[] Dispatch(string arg, out time)
{
if (arg == null)
throw new ArgumentNullException("arg");
ComputeParam[] array = new ComputeParam[1];
int argInt;
if (int.TryParse(arg, out argInt) && 0 <= argInt && argInt <= 20)
{
array[0] = new ComputeParam(argInt);
time = 0; // You must always set an out param
}
else if (arg.StartsWith("/t")
{
time = new Options().Option(arg);
}
return array;
}
i
是什么?这总是等于0
?object
s的数组,而不是ComputeParam
s?上述代码可能会根据您的答案发生重大变化。
答案 5 :(得分:0)
作为Shai答案的进一步阐述,您可以使ArgsParser
保持输出参数本身。如果感觉正确,解析可以在其构造函数中完成:
public class ArgsParser
{
public object[] aObj { get; set;}
public DateTime dtTime {get; set;}
public ArgsParser(string arg)
{
int time;
int i = 0;
aObj = new object[10];
if (int.Parse(arg) >= 0 && int.Parse(arg) <= 20)
{
aObj[i] = new ComputeParam(int.Parse(arg));
}
else
{
if (arg[0] == '/' && arg[1] == 't')
{
Options opt = new Options();
// Is this where you need to time?
dtTime = opt.Option(arg);
}
}
}
}
}
我认为ArgsParser仅用于参数解析