1.关于重载运算符
2.包含与委托(不太明白)
class Program { class Radio { protected bool on_off; public void On() { if (!on_off )Console .WriteLine ("Radio is now on!"); on_off = true; } public void Off() { if (!on_off) Console.WriteLine("Radio is now off!"); on_off = false; } } } class AlarmClock { private int currentTime; private int alarmTime; protected virtual void SoundAlarm() { Console.WriteLine("Buzz!"); } public void Run() { for (int currentTime = 0; currentTime < 43200; currentTime++) { SetCurrentTime(currentTime); if (GetCurrentTime() == GetAlarmTime()) { Console.WriteLine("Current Time = {0}!", currentTime); SoundAlarm(); break; } } } public int GetCurrentTime() { return currentTime; } public void SetCurrentTime(int aTime) { currentTime = aTime; } public int GetAlarmTime() { return alarmTime; } public void SetAlarmTime(int aTime) { alarmTime = aTime; } } class ClockRadio : AlarmClock { private Radio radio;//声明其他成员的变量 public bool radioAlarm; public ClockRadio() { radio = new Radio(); radioAlarm = false; } //-------------Delegate to Radio--------------- public void RadioOn() { radio.On(); } public void RadioOff() { radio.Off(); } //--------------Overridde AlarmClock----------------- protected override void SoundAlarm() { if (radioAlarm) { RadioOn(); } else { base.SoundAlarm(); } } //-------New ClockRadio functionalitiy------------ public void SetRadioAlarm(bool useRadio) { radioAlarm = useRadio; } } class ContInh { static int Main(string[] args) { ClockRadio clockRadio; clockRadio = new ClockRadio(); clockRadio.SetRadioAlarm(true); clockRadio.SetAlarmTime(100); clockRadio.Run(); //wait for user to acknowledge the results Console.WriteLine("Hit Enter to terminate...."); Console.Read(); return 0; } }
错误提示:
错误 1 未能找到类型或命名空间名称“Radio”(是否缺少 using 指令或程序集引用?) c:\users\administrator\documents\visual studio 2012\Projects\ConsoleApplication36\ConsoleApplication36\Program.cs 75 17 ConsoleApplication36
is 关键字与as关键字
//类 类对象 方法 接口 public interface IPrintMessage { void Print(); } class Class1 { public void Print() { Console.WriteLine("from class1 "); } } class Class2 : IPrintMessage { public void Print() { Console.WriteLine("from class2"); } } class Mainclass { public static void Main() { PrintClass PrintObject = new PrintClass (); PrintObject.PrintMessage(); } } class PrintClass { public void PrintMessage() { Class1 Object1 = new Class1(); Class2 Object2 = new Class2(); PrintMessageFromObject(Object1); PrintMessageFromObject(Object2); } private void PrintMessageFromObject(object obj) { if (obj is IPrintMessage)//对象标识符 关键字is 接口标识符 { IPrintMessage PrintMessage; PrintMessage = (IPrintMessage)obj;//访问对象接口实现时 先声明一个接口类型的变量 然后将对象类型转换成接口类型 PrintMessage.Print(); } } }
private void PrintMessageFromObject(object obj) { IPrintMessage PrintMessage; PrintMessage = obj as IPrintMessage;//对象标识符 关键字as 接口标识符 if (PrintMessage != null)//c#关键字null(空值) PrintMessage.Print(); }