Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

c# - What does {0} stands for in Console.WriteLine?

Given the code :

// 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

The output of the code is :

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

What does the {0} in Console.WriteLine("Person details - {0}", person); stands for ? How come it's replaced by Name..... ?

When I put {1} instead of {0} I get an exception ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As you can see, There's a code on your person object that returns a string, Console checks for If a type of string with name of ToString exists on your object class or not, If exists then It returns your string:

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

And {0} Is a formatted message, When you define It to {0} It means printing/formatting the zero Index object that you Inserted Into params arguments of your function. It's a zero based number that gets the index of object you want, Here's an example:

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!

When you say {0} It gets C# or the [0] of your object[].


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...