{0} 在 Console.WriteLine 中代表什么?

JAN*_*JAN 1 c# console console.writeline

鉴于代码:

// person.cs
using System;

// #if false

class Person
{
    private string myName = "N/A";
    private int myAge = 0;

    // Declare a Name property of type string:
    public string Name
    {
        get
        {
            return myName;
        }
        set
        {
            myName = value;
        }
    }

    // Declare an Age property of type int:
    public int Age
    {
        get
        {
            return myAge;
        }
        set
        {
            myAge = value;
        }
    }

    public override string ToString()
    {
        return "Name = " + Name + ", Age = " + Age;
    }

    public static void Main()
    {
        Console.WriteLine("Simple Properties");

        // Create a new Person object:
        Person person = new Person();

        // Print out the name and the age associated with the person:
        Console.WriteLine("Person details - {0}", person);

        // Set some values on the person object:
        person.Name = "Joe";
        person.Age = 99;
        Console.WriteLine("Person details - {0}", person);

        // Increment the Age property:
        person.Age += 1;
        Console.WriteLine("Person details - {0}", person);
    }
}

// #endif
Run Code Online (Sandbox Code Playgroud)

代码的输出是:

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100
Run Code Online (Sandbox Code Playgroud)

什么是{0}Console.WriteLine("Person details - {0}", person);看台上呢?怎么换成了Name.....

当我把{1}而不是{0}我得到一个例外......

111*_*111 5

如您所见,您的 person 对象上有一个返回字符串的代码,控制台检查您的对象类中是否存在名称为 ToString 的字符串类型,如果存在,则返回您的字符串:

public override string ToString()
{
     return "Name = " + Name + ", Age = " + Age;
}
Run Code Online (Sandbox Code Playgroud)

而 {0} 是格式化消息,当您将其定义为 {0} 时,这意味着打印/格式化您插入到函数的 params 参数中的零索引对象。这是一个从零开始的数字,用于获取所需对象的索引,这是一个示例:

Console.WriteLine("{0} Is great, {1} Do you think of It? {2} Think {0} Is great!", "C#", "What", "I");

// C# Is great, What do you think of It? I think C# Is great!
Run Code Online (Sandbox Code Playgroud)

当您说 {0} 时,它会获取 C# 或对象 [] 的 [0]。