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

时间:2013-10-23 16:56:37

标签: 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

代码的输出是:

Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100

{0}中的Console.WriteLine("Person details - {0}", person);代表什么? 它怎么被Name.....取代?

当我将{1}代替{0}时,我得到了一个例外......

5 个答案:

答案 0 :(得分:4)

它指的是参数的索引号。 例如,如果要打印多个变量,可以执行以下操作:

Console.WriteLine("Person details - {0} {1}", person1, person2)

答案 1 :(得分:3)

正如您所看到的,您的person对象上有一个返回字符串的代码,Console检查对象类是否存在名称为ToString的字符串,如果存在则返回您的字符串:

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

和{0}是格式化的消息,当它定义为{0}时它意味着打印/格式化您插入函数的参数参数的零索引对象。它是一个基于零的数字,可以获得所需的对象索引,这是一个例子:

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!

当你说{0}它得到C#或对象[]的[0]时。

答案 2 :(得分:2)

Write / WriteLine调用中,第一个参数是格式字符串。格式说明符用大括号括起来。每个说明符包含一个参数的数字引用,该参数需要“插入”格式字符串作为所述说明符的替换,以及相应数据项的可选格式化指令。

Console.WriteLine(
    "You collected {0} items of the {1} items available.", // Format string
    itemsCollected,                                        // Will replace {0}
    itemsTotal                                             // Will replace {1}
);

这类似于C / C ++中的printf,其中%...指定参数列表中相应项的格式。一个主要的区别是printf函数族要求参数及其格式说明符以相同的顺序列出。

答案 3 :(得分:1)

它指的是给定变量的索引(第一个变量,第二个变量等),它们要写入其内容。你只有一个变量(person),这就是为什么你只能设置第一个索引(0)。

Console.WriteLine("Person details - {0}", person); {0}表示:将第一个变量的内容写在{0}所在的位置。

答案 4 :(得分:1)

了解这些内容的最佳方式是本网站的示例部分:

Console.WriteLine Method (String, Object)

相关问题