嘿,伙计们,我是C#的新手,我想知道是否有一种简单的方法可以将字符串作为多个参数进行传递。下面是一个例子:
我想传递给一个接受这些参数的函数:
DoStuff(int a, string b, string c, string d)我有一个字符串,比如“字符串e”,它包含以下内容: 1,a,b,c
所以我想这样调用这个函数,DoStuff(e)。但这当然会导致错误,因为它需要更多的参数。有没有一种简单的方法可以将我的参数字符串传递给函数?
编辑:感谢所有关于函数重载的建议。这个函数是一个类构造函数,它能有重载吗?下面是代码
arrayvariable[count] = new DoStuff(e);发布于 2011-05-25 05:56:38
您需要对接受单个字符串的方法进行重载。然后,它可以拆分字符串并创建适当的参数。
例如:
void DoStuff(int a, string b, string c, string d)
{
// Do your stuff...
}
void DoStuff(string parameters)
{
var split = parameters.Split(',');
if (split.Length != 4)
throw new ArgumentException("Wrong number of parameters in input string");
int a;
if (!int.TryParse(split[0], out a)
throw new ArgumentException("First parameter in input string is not an integer");
// Call the original
this.DoStuff(a, split[1], split[2], split[3]);
}当然,如果这是您经常做的事情,那么可以将其重构为一个方法,该方法可以使字符串解析更加通用和可重用。
发布于 2011-05-25 06:00:19
public void DoStuff( int a, string b, string c, string d )
{
//your code here
}
public void DoStuff( string e )
{
string[] splitE = e.Split( ',' );
int a;
int.TryParse( splitE[0], out a );
DoStuff( a, splitE[1], splitE[2], splitE[3] );
}您需要对int的拆分和解析进行额外的错误检查,但这应该已经完成了
发布于 2011-05-25 07:56:47
public void DoStuff(int a, params String[] strings)
{
foreach (String s in strings)
{
do something else;
}
}“params”属性指示DoStuff可以有0个或更多字符串作为参数,编译器会自动将它们填充到一个数组中。
https://stackoverflow.com/questions/6117398
复制相似问题