我对 C# 编程非常陌生,在 C++ 和 HTML 中具有浅色背景,所以我几乎是从头开始。我一直在看msdn教程,特别是属性教程,到目前为止我只有一个部分不明白。代码中有一部分是这样的:
// person.cs
using System;
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);
}
}
程序的输出是这样的:
Simple Properties
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100
现在我知道 {0} 实际上是一个引用代码的一部分的占位符,在这种情况下它是“人”,但我不明白这部分是如何:
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
列在“人”下。我看不到与“姓名”和“年龄”之间的联系。有人可以突出显示建立连接的代码部分并可能对其进行解释(如果要求不多的话)?非常感谢您提前。