我想有一个返回数组的函数。我首先使用void函数对此进行了测试,但是控制台中的字符串为空,并且没有找到我的保管库。
private void getValueOfRadio() {
string[,] arrayUrl = new String[4, 3] {
{ "xx0", "xxx0", "xxxx0" },
{ "xx1", "xxx1", "xxxx1" },
{ "xx2", "xxx2", "xxxx2" },
{ "xx3", "xxx3", "xxxx3" }
};
var checkedRadioButton = groupUrl
.Controls
.OfType<RadioButton>()
.FirstOrDefault(x => x.Checked == true);
int i = 0;
if (checkedRadioButton != null) {
switch (checkedRadioButton.Text) {
case "MK-Live":
i = 1;
break;
case "MK-Test":
i = 2;
break;
case "Roland Test":
i = 3;
break;
default:
i = 0;
break;
}
}
string[] returnArray = new string[] {
arrayUrl[i, 0], arrayUrl[i, 1], arrayUrl[i, 2] };
Console.WriteLine(returnArray);
}
答案 0 :(得分:2)
让我们提取一些方法:RowIndexFromButton
-我们要打印哪一行(基于单选按钮),RowFromArray
-从2d数组中提取行。
private int RowIndexFromButton() {
var checkedRadioButton = groupUrl
.Controls
.OfType<RadioButton>()
.FirstOrDefault(x => x.Checked);
if (checkedRadioButton == null)
return -1; //TODO: or 0 if we want to get 0th record
switch (checkedRadioButton.Text) {
case "MK-Live":
return 1;
case "MK-Test":
return 2;
case "Roland Test":
return 3;
default:
return 0;
}
}
private static IEnumerable<T> RowFromArray<T>(T[,] array, int row) {
if (null == array)
throw new ArgumentNullException(nameof(array));
else if (row < array.GetLowerBound(0) || row > array.GetUpperBound(0))
yield break;
for (int i = array.GetLowerBound(1); i <= array.GetUpperBound(1); ++i)
yield return array[row, i];
}
然后,我们可以轻松地将两种方法结合在一起:
我想有一个返回数组的函数
private T[] RowFromButton<T>(T[,] array) {
return RowFromArray(array, RowIndexFromButton()).ToArray();
}
并使用它:
string[,] arrayUrl = new String[4, 3] {
{ "xx0", "xxx0", "xxxx0" },
{ "xx1", "xxx1", "xxxx1" },
{ "xx2", "xxx2", "xxxx2" },
{ "xx3", "xxx3", "xxxx3" }
};
string[] returnArray = RowFromButton(arrayUrl);
// When printing collection (array) we should join items (e.g. with space)
Console.WriteLine(string.Join(" ", returnArray));
答案 1 :(得分:1)
关于Console.WriteLine Method
,有一些重载,例如:
WriteLine(String)
将指定的字符串值和当前的行终止符写入标准输出流。WriteLine(Char [])
将指定的Unicode字符数组和当前的行终止符写入标准输出流。WriteLine(Object)
将当前行终止符写入标准输出流。将指定对象的文本表示形式,然后将当前行终止符写入标准输出流。...
由于没有WriteLine(String[])
之类的重载,我们
可以使用WriteLine(String)
来打印string[]
,例如
foreach
逐一打印字符串项string.Join
字符串数组中的项目转换为一个字符串,然后将其打印出来帖子中的代码段
string[] returnArray = new string[] { arrayUrl[i, 0], arrayUrl[i, 1], arrayUrl[i, 2] };
// Console.WriteLine(returnArray); // <-- the original code
foreach(var s in returnArray) {
Console.WriteLine(s);
}
//or
Console.WriteLine(string.Join(" ", returnArray));
一些跟进,
char[] cArray = new char[] {'a', 'b', 'c'};
Console.WriteLine(cArray); // prints "abc"
那是因为有一个重载WriteLine(Char[])
要打印Char[]