假设我有一个Car
类并且该类包含一个Radio
对象。看起来像
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();
关于何时应将自定义类型保留为字段与将其设为属性的一些一般准则是什么?