我正在读一本名为“Visual C#2012 Programming”的书,我想出了以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Ch05StringManupulationEx
{
class Program
{
static void Main(string[] args)
{
string myString = "String with small s";
char[] myChar = myString.ToCharArray();
foreach (char whatever in myString)
{
Console.WriteLine("{0}", whatever);
}
Console.Write("\nyou have entered {0} characters in String ",myString.Length);
Console.ReadKey();
}
}
}
我不知道aurthor在线做什么:
的 char[] myChar = myString.ToCharArray();
因为他没有在代码中的任何地方使用名为 myChar 的变量,即使我评论了该行并编译了程序输出相同,任何人都可以解释此代码中此行的用途是什么?
答案 0 :(得分:4)
可能他们忘了删除该行或显示它做了什么,它是一个字符数组,一个字符串中充满了字符,字符串的每个字母都是一个字符,您可以使用零访问任何这些数组基于数字,例如:
string a = "Hello";
// Prints e
Console.WriteLine(a[2]);
您可以将此行更改为myChar以理解,它与字符串数组相同,这意味着字符串是字符数组,这是示例:
foreach (char whatever in myChar)
{
Console.WriteLine("{0}", whatever);
}