1 回答

TA貢獻1818條經驗 獲得超7個贊
你真的應該澄清你遇到的問題;請隨時閱讀如何提問。
基本循環
就您的問題而言(根據我的理解),您希望重復調用一個方法并讓該方法返回與當前調用對應的字符串的索引。我會查看for 循環和string.Substring(int),您也可以將字符串作為字符數組訪問(我在下面這樣做)。
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;
}
如果您想逃避上面的循環,您需要添加一些條件邏輯來確定循環是否應該被破壞,或者只對GetCharacter(string, int)提供的方法進行單獨調用而不是循環。此外,i如果確實需要,您應該只修改迭代變量;在這種情況下,您可以切換到更合適的while 循環:
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;
}
獲取角色(表情身體 vs 全身)
C# 6 引入了將方法編寫為表達式的能力;寫成表達式的方法稱為Expression-Bodied-Member。例如,以下兩種方法的功能完全相同:
static char GetCharacter(string data, int index) => data[index];
static char GetCharacter(string data, int index) {
return data[index];
}
表達式主體定義允許您以非常簡潔、易讀的形式提供成員的實現。只要任何受支持成員(例如方法或屬性)的邏輯包含單個表達式,就可以使用表達式主體定義。
- 1 回答
- 0 關注
- 484 瀏覽
添加回答
舉報