ここに、年齢、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++);
}
}
}