Array.ToString() 返回 System.Char[] c# [英] Array.ToString() returning System.Char[] c#
问题描述
我正在做一个刽子手游戏,在游戏开始时,玩家必须猜测的单词被打印为星星.在尝试编写一次之后,我刚刚开始再次制作它,并且只有我无法修复的凌乱代码.所以我决定最好再写一遍.唯一的问题是,当我尝试使用 array.ToString() 打印出我的数组时;它只返回 System.char[].见下文.
Im making a hangman game, at the start of the game the word that the player must guess is printed as stars. I have just started making it again after attempting to write it once and just having messy code that i couldn't bug fix. So I decided it best to write it again. The only problem is, when i try to get my array to print out by using array.ToString(); it just returns System.char[]. See below.
代码:
class Program
{
static void Main(string[] args)
{
string PlayerOneWord;
string PlayerTwoGuess;
int lives = 5;
Console.WriteLine("Welcome to hangman!\n PLayer one, Please enter the word which player Two needs to guess!");
PlayerOneWord = Console.ReadLine().ToLower();
var stars = new char[PlayerOneWord.Length];
for (int i = 0; i < stars.Length ; i++)
{
stars[i] = '*';
}
string StarString = stars.ToString();
Console.Write("Word to Guess: {0}" , StarString);
Console.ReadLine();
}
}
输出:
输出应该是 Word to guess: Hello
.
请有人解释为什么会发生这种情况,因为这不是我第一次遇到这个问题.
Please will someone explain why this is happening as its not the first time I have run into this problem.
推荐答案
在简单数组上调用 ToString
只会返回 "T[]"
而不管类型是什么 >T
是.它对 char[]
没有任何特殊处理.
Calling ToString
on a simple array only returns "T[]"
regardless what the type T
is. It doesn't have any special handling for char[]
.
要将 char[]
转换为 string
,您可以使用:
To convert a char[]
to string
you can use:
string s = new string(charArray);
但是对于您的具体问题,有一个更简单的解决方案:
But for your concrete problem there is an even simpler solution:
string stars = new string('*', PlayerOneWord.Length);
构造函数 public String(char c, int count)
重复 c
count
次.
这篇关于Array.ToString() 返回 System.Char[] c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!