Exemplo n.º 1
0
 static void TryCauseMayhem(object mayhemCauser)
 {
     Console.WriteLine("mayhemCauser is a {0}", mayhemCauser.GetType().Name);
     if (typeof(ICauseMahem).IsAssignableFrom(mayhemCauser.GetType()))
     {
         try
         {
             //Here we un-box the mayhem causer back to a usable type.
             ICauseMahem castedCauser = (ICauseMahem)mayhemCauser;
             castedCauser.PerformMayhem();
         }
         catch (MayhemException mayhem)
         {
             Console.WriteLine("Broken spectacularly!");
         }
         catch
         {
             Console.WriteLine("It wasn't mayhem, but at least it broke in a mess");
         }
     }
     else
     {
         Console.WriteLine("We couldn't cause any mayhem");
     }
 }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Cleaner simpleCleaner = new Cleaner();

            //Boxing occurs here to box the Cleaner into a more generic object type.
            TryCauseMayhem(simpleCleaner);
            TryCleanup(simpleCleaner);

            MayhemCauser simpleMayhem = new MayhemCauser();

            TryCauseMayhem(simpleMayhem);
            TryCleanup(simpleMayhem);

            IClean      catHatClean  = new CatHat();
            ICauseMahem catHatMayhem = catHatClean as ICauseMahem; //This works because cat hat implements both interfaces.

            TryCauseMayhem(catHatClean);                           //These will both work because of the multiple interface implementation.
            TryCleanup(catHatMayhem);

            ThingOne thingOne = new ThingOne();

            TryCauseMayhem(thingOne);
            TryCleanup(thingOne);

            ThingTwo thingTwo = new ThingTwo();

            TryCauseMayhem(thingTwo);
            TryCleanup(thingTwo);

            Console.ReadKey();
        }