Console.Write(" ");
will delete the asterisk character from the screen, but you do not have any code within your else
block that removes the previously entered character from your pass
string variable.
Here's the relevant working code that should do what you require:
var pass = string.Empty;
ConsoleKey key;
do
{
var keyInfo = Console.ReadKey(intercept: true);
key = keyInfo.Key;
if (key == ConsoleKey.Backspace && pass.Length > 0)
{
Console.Write(" ");
pass = pass[0..^1];
}
else if (!char.IsControl(keyInfo.KeyChar))
{
Console.Write("*");
pass += keyInfo.KeyChar;
}
} while (key != ConsoleKey.Enter);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…