声明了属性后,可像使用类的字段那样使用这些属性。
private int myVar;
public int MyProperty
{
get { return myVar;}
set { myVar = value;}
}
public int MyProperty
{
get { return myVar;}
set { myVar = value;}
}
这使得获取和设置属性值时都可以使用非常自然的语法,如以下语句中所示:
person.Name = "Joe";
person.Age = 99;
class Person
{
private string m_name = "N/A";
private int m_Age = 0;
// Declare a Name property of type string:
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
// Declare an Age property of type int:
public int Age
{
get
{
return m_Age;
}
set
{
m_Age = value;
}
}
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
}
class TestPerson
{
static void Main()
{
// Create a new Person object:
Person person = new Person();
// Print out the name and the age associated with the person:
System.Console.WriteLine("Person details - {0}", person);
// Set some values on the person object:
person.Name = "Joe";
person.Age = 99;
System.Console.WriteLine("Person details - {0}", person);
// Increment the Age property:
person.Age += 1;
System.Console.WriteLine("Person details - {0}", person);
}
}
/*输出
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100
*/
person.Age = 99;
class Person
{
private string m_name = "N/A";
private int m_Age = 0;
// Declare a Name property of type string:
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
// Declare an Age property of type int:
public int Age
{
get
{
return m_Age;
}
set
{
m_Age = value;
}
}
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
}
class TestPerson
{
static void Main()
{
// Create a new Person object:
Person person = new Person();
// Print out the name and the age associated with the person:
System.Console.WriteLine("Person details - {0}", person);
// Set some values on the person object:
person.Name = "Joe";
person.Age = 99;
System.Console.WriteLine("Person details - {0}", person);
// Increment the Age property:
person.Age += 1;
System.Console.WriteLine("Person details - {0}", person);
}
}
/*输出
Person details - Name = N/A, Age = 0
Person details - Name = Joe, Age = 99
Person details - Name = Joe, Age = 100
*/