您确实应该澄清您遇到的问题;欢迎阅读How to Ask。
基本循环
就您的问题而言(根据我的理解),您希望重复调用一个方法并让该方法返回与当前调用对应的字符串的索引。我会查看for loop 和string.Substring(int),您也可以将字符串作为char 数组访问(我在下面进行)。
static void Main() {
string myString = "SomeStringData";
for (int i = 0; i < myString.Length; i++)
Console.Write(GetCharacter(myString, i));
}
static char GetCharacter(string data, int index) => data[index];
可以修改上面的代码以进行顺序调用,直到您需要停止循环,这将满足您在到达字符串末尾时返回第一个索引的条件:
string myString = "abc";
for (int i = 0; i < myString.Length; i++) {
Console.Write(GetCharacter(myString, i);
// This will reset the loop to make sequential calls.
if (i == myString.Length)
i = 0;
}
如果您希望摆脱上面的循环,您需要添加一些conditional logic 来确定循环是否应该是broken,或者不要循环,只需单独调用提供的GetCharacter(string, int) 方法。此外,如果您确实需要,您应该只修改迭代变量i;在这种情况下,您可以切换到更合适的while loop:
string myString = "abc";
string response = string.Empty;
int index = 0;
while (response.TrimEnd().ToUpper() != "END") {
Console.WriteLine(GetCharacter(myString, index++));
Console.WriteLine("If you wish to end the test please enter 'END'.");
response = Console.ReadLine();
if (index > myString.Length)
index = 0;
}
获取字符(表达式主体与全身)
C# 6 引入了将方法编写为表达式的能力;写成表达式的方法称为Expression-Bodied-Member。例如,以下两种方法的功能完全相同:
static char GetCharacter(string data, int index) => data[index];
static char GetCharacter(string data, int index) {
return data[index];
}
表达式主体定义让您以非常简洁易读的形式提供成员的实现。只要任何受支持成员(例如方法或属性)的逻辑由单个表达式组成,您就可以使用表达式主体定义。