set: A set accessor is used to assign a new value.(只是增加一些變數(pulbic)的方便性,asign時, 會跑進來)
get: A get property accessor is used to return the property value.(只是增加一些變數(pulbic)的方便性, 取值時, 會跑進來)
value: The value keyword is used to define the value being assigned by the set accessor.(即assign進來的值)
請看下面範例(來源:微軟官網, 如有侵權, 請來告知, 馬上刪除):
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
class Program
{
static void Main()
{
TimePeriod t = new TimePeriod();
// Assigning the Hours property causes the 'set' accessor to be called.
t.Hours = 24;
// Evaluating the Hours property causes the 'get' accessor to be called.
System.Console.WriteLine("Time in hours: " + t.Hours);
}
}
// Output: Time in hours: 24
------------------------------------------------------------
This is an example of a get accessor in an auto-implemented property
class TimePeriod2
{
public double Hours { get; set; }
}
沒有留言:
張貼留言