假設我有Car
類,並且該類包含Radio
對象。它看起來像何時自定義類型屬性vs會員
class Radio
{
public string Model { get; set; }
private List<string> myChannels = new List<string>();
public List<string> PresetChannels
{
get { return myChannels; }
set { myChannels = value; }
}
private bool radioState;
public void ToggleRadio()
{
if (!radioState)
radioState = true;
else
radioState = false;
}
private string selectedChannel = string.Empty;
//
public void SetStation(int radioButton, string channelName)
{
while (!ValidateRadioButtonNumber(radioButton))
{
Console.Write("Index out of range, choose another value: ");
radioButton = Convert.ToInt32(Console.ReadLine());
}
PresetChannels[radioButton] = channelName;
Console.WriteLine("The {0} radio button was set to {1}",radioButton,channelName);
}
private bool ValidateRadioButtonNumber(int radioButton)
{
if (radioButton < 0 || radioButton > 5)
return false;
else
return true;
}
//
public void SelectChannel(int radioButton)
{
while (!ValidateRadioButtonNumber(radioButton))
{
Console.Write("Index out of range, choose another value: ");
radioButton = Convert.ToInt32(Console.ReadLine());
}
selectedChannel = PresetChannels[radioButton];
Console.WriteLine(PresetChannels[radioButton]);
}
public Radio()
{
PresetChannels = new List<string>();
PresetChannels.Capacity = 5;
//initialize every element in the list at runtime
//so the user can set any station they wish
for (int i = 0; i < PresetChannels.Capacity; i++)
{
PresetChannels.Add(string.Empty);
}
}
}
與Car
類像
public class Car
{
public int Year { get; set; }
public string Model { get; set; }
private Radio radio;
public Radio MyRadio { get; set; }
//initialize the radio of the car
public Car()
{
radio = new Radio();
MyRadio = new Radio();
}
//containment
public void SelectStation(int radioButton)
{
radio.SelectChannel(radioButton);
}
public void SetStation(int radioButton, string channelName)
{
radio.SetStation(radioButton, channelName);
}
public void ToggleRadio()
{
radio.ToggleRadio();
}
}
如果我讓設計與MyRadio
類的屬性,那麼什麼是遏制的地步?如果Radio
的一個屬性擁有一個私有設置器,並且您試圖在Main
方法中設置該值,它將無法編譯,對吧?
Car c = new Car();
c.SetStation(0, "99.2");
c.SetStation(10, "100"); //works
c.SelectStation(120);
Car c2 = new Car();
c2.MyRadio.SetStation(0, "99.0");//works
Console.ReadLine();
什麼是何時應該保持一個自定義類型的字段與使它屬性的一般準則?
如果您希望對其進行外部修改,或者只在內部進行修改,則將其設爲屬性。 – Mansfield
屬性是成員的子集。和田地一樣。 –
[自動實現的getters和setter與公共字段]的可能重複(http://stackoverflow.com/questions/111461/auto-implemented-getters-and-setters-vs-public-fields) – nawfal