在C#中,可以使用Console.ReadKey方法來隱藏用戶輸入的內容。具體代碼如下所示:
using System;
class Program
{
static void Main()
{
Console.Write("請輸入密碼:");
string password = "";
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter)
{
password += key.KeyChar;
Console.Write("*");
}
else
{
if (key.Key == ConsoleKey.Backspace && password.Length > 0)
{
password = password.Substring(0, (password.Length - 1));
Console.Write("\b \b");
}
}
}
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
Console.WriteLine("您輸入的密碼是:" + password);
}
}
上面的代碼中,用戶輸入密碼時,控制臺會顯示星號(*)代替用戶輸入的字符,從而隱藏密碼內容。