我目前正在嘗試了解 c# 和方法/函式。我只是想讓函式PlayerName()回傳一個可以存盤在變數中的值playerName。我有這段代碼,但我不明白出了什么問題。沒有while回圈,它可以作業。但是,一旦實作了 while 回圈,就會出現問題return playerName(使用未分配的區域變數“playerName”)。我不明白它是如何未分配的。
namespace methodtest
{
internal class Program
{
static void Main(string[] args)
{
string playerName = PlayerName();
}
static string PlayerName()
{
bool notCorrect = true;
string playerName;
while (notCorrect)
{
Console.Write("Type your name: ");
playerName = Console.ReadLine();
Console.WriteLine($"You typed {playerName}. Continue? 'y'/'n'");
string correct = Console.ReadLine();
if (correct == "n")
{
Console.WriteLine("Try again.");
}
else if (correct == "y")
{
notCorrect = false;
}
}
return playerName;
}
}
}
uj5u.com熱心網友回復:
您收到的錯誤訊息是CS0165: Use of unassigned local variable 'playerName'
編譯器告訴您需要提供playerName初始值。您可以使用以下任何您認為合適的方法對其進行初始化。
string.Empty要么""
null
舉個例子
string playerName = string.Empty;
uj5u.com熱心網友回復:
首先 - 您需要初始化 playerName 變數 (string playerName = "") 或 (string.Empty)
第二 - 您沒有顯示 playerName,只是將 PlayerName() 的結果分配給變數。您需要顯示變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438960.html
