以下是源代码:
注意红色部分,为什么用GrossSales和CommissionRate,而不是grossSales和commissionRate ??
抑或是两种方法相同??
public class CommissionEmployee : object
{
private string firstName;
private string lastName;
private string socialSecurityNumber;
private decimal grossSales; // gross weekly sales
private decimal commissionRate; // commission percentage
// five-parameter constructor
public CommissionEmployee( string first, string last, string ssn,
decimal sales, decimal rate )
{
// implicit call to object constructor occurs here
firstName = first;
lastName = last;
socialSecurityNumber = ssn;
GrossSales = sales; // validate gross sales via property
CommissionRate = rate; // validate commission rate via property
} // end five-parameter CommissionEmployee constructor
// read-only property that gets commission employee's first name
public string FirstName
{
get
{
return firstName;
} // end get
} // end property FirstName
// read-only property that gets commission employee's last name
public string LastName
{
get
{
return lastName;
} // end get
} // end property LastName
// read-only property that gets
// commission employee's social security number
public string SocialSecurityNumber
{
get
{
return socialSecurityNumber;
} // end get
} // end property SocialSecurityNumber
// property that gets and sets commission employee's gross sales
public decimal GrossSales
{
get
{
return grossSales;
} // end get
set
{
grossSales = ( value < 0 ) ? 0 : value;
} // end set
} // end property GrossSales
// property that gets and sets commission employee's commission rate
public decimal CommissionRate
{
get
{
return commissionRate;
} // end get
set
{
commissionRate = ( value > 0 && value < 1 ) ? value : 0;
} // end set
} // end property CommissionRate
// calculate commission employee's pay
public decimal Earnings()
{
return commissionRate * grossSales;
} // end method Earnings
// return string representation of CommissionEmployee object
public override string ToString()
{
return string.Format(
"{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}",
"commission employee", FirstName, LastName,
"social security number", SocialSecurityNumber,
"gross sales", GrossSales, "commission rate", CommissionRate );
} // end method ToString
} // end class CommissionEmployee
属性GrossSales和CommissionRate都是可写的,如果直接对变量grossSales和commissionRate直接赋值,在性能上会好点,但是,这两个属性的Set方法里有数据安全检测,假如在构造函数里直接对变量赋值,那就也要在构造函数里写安全检测代码,这样同一段代码两个地方编写,一来重复劳动,二来容易引起代码不一致的情况发生,以后维护不方便。
你这个问题很简单,很多人都能回答,但是却不回答。。。你知道为什么吗?
太菜了。。。LZ要继续补充C#基础。。。
请看看属性,是将公有字段进行 封装——》重构,更好得保护程序。属性包含set(只读属性)和get(只写属性)构造器。
private decimal grossSales;
public decimal GrossSales(公有的GrossSales)
{
get//是只读,因为这里没有set(写),用户只能读取
{
return grossSales;//并将值返回到程序中的私有grossSales字段
}
如果你还不明白,你可以自己定义一个
decimal GrossSales ; 然后鼠标在上面右击——》重构——》封装字段——》然后确定。
自己对照着变化看看是什么发生了变化,查的话,可以查属性 关键字