namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string word = "Shazam!";
Console.WriteLine(word.ToString().ToString().ToString().ToString());
Console.ReadKey();
}
}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我为什么我可以多次调用ToString()?好奇,谢谢!
因为string它本身有一个ToString()方法(所有对象都有).
你打电话ToString()先上word,然后在该调用的结果,那么结果是调用等,基本上每个后续调用作用于前一个结果.
它ToString()当然不限于此.例如:
int x = new object().ToString().Substring(0, 2).Length;
Run Code Online (Sandbox Code Playgroud)
它调用ToString()一个新对象,然后调用Substring返回的字符串,然后调用Length该子字符串.