示例代码(替代代码如下),
// person.cs
using System;
class Person
{
private string myName ="N/A";
// Declare a Name property of type string:
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public override string ToString()
{
return "Name = " + Name;
}
public static void Main()
{
Person person = new Person();
Console.WriteLine("Person details - {0}", person);
person.Name = "Joe";
Console.WriteLine("Person details - {0}", person);
}
}
不能直接写,把myName
private改成public,不需要再声明一个public变量Name,也不需要get和set?
替代代码
// person.cs
using System;
class Person
{
public string myName ="N/A";
public override string ToString()
{
return "Name = " + myName;
}
public static void Main()
{
Person person = new Person();
Console.WriteLine("Person details - {0}", person);
person.myName = "Joe";
Console.WriteLine("Person details - {0}", person);
}
}