我在这里有一个程序片段,它允许创建一个具有年龄、id、姓名和工资等简单属性的 Employee 对象。只是在玩它,我注意到
Console.WriteLine(joe.Age+1); is my Main() method returns one,
但Console.WriteLine(joe.Age++);
返回 0。我知道根据构造函数将 Age 属性初始化为 0,但为什么不使用 ++ 运算符添加 1? 编辑:我找到了奇怪行为的根源。在我拥有的 Age 属性中empAge=Age
,它应该等于value
来源:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EmployeeApp
{
class Employee
{
//field data
//notice the the fields are declared as private
//these fields are used in the constructors
private string empName;
private int empID;
private float currPay;
private int empAge;
//properties! private field data should be accessed via public properties
//note that properties don't use parentheses ()
//within the set scope you see the 'value' contextual keyword
//it represents the value being assigned by the caller and it will always be the same
//underlying data type as the property itself
public int Age
{
get { return empAge; }
set { empAge = Age; }
}
public string Name
{
get { return empName; }
set
{
if (value.Length > 15)
Console.WriteLine("this name is too long.");
else
empName = value;
}
}
public int ID
{
get { return empID; }
set { empID = value; }
}
public float pay
{
get { return currPay; }
set { currPay = value; }
}
//constructors
public Employee() { }
public Employee(string name, int id, float pay, int age)
{
empName = name;
empID = id;
currPay = pay;
empAge = age;
}
//methods
//the int parameter that this method takes will come from somewhere in the Main method
//currpay is a private field
public void GiveBonus(float amount)
{
currPay += amount;
}
public void DisplayStats()
{
Console.WriteLine("name: {0}", empName);
Console.WriteLine("ID: {0}", empID);
Console.WriteLine("pay: {0}", currPay);
Console.WriteLine("age: {0}", empAge);
}
}
}
主要方法在这里
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//Encapsulation using traditional accessors/mutators or get/set methods
//the role of a get method is to return to the caller the current value of the underlying state data
//a set method allows the caller ot change the current value of the state data
//you need to have a getter and a setter for every field that the class has
namespace EmployeeApp
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("fun with encapsulation");
//Employee emp = new Employee("marvin", 456, 4000, 56);
//emp.GiveBonus(3);
// emp.DisplayStats();
// emp.Name = "wilson";
// emp.DisplayStats();
Employee joe = new Employee();
Console.WriteLine(joe.Age++);
}
}
}