Csharp Inheritance And Fields
In this example I try to be stupid in my implementation of a family of classes and then work around my stupid planning with a number of interesting functions to examine classes.
Also see this thread from microsoft.public.dotnet.languages.csharp: [1]
The Code
The code is available here: [2]
This is pretty much the inheritance diagram. In musiCar we introduce the member hasStereo. In homeMadeCar we add an identical member.
// car ----- musicar ---- nicecar // \ \ // \ +------ oldcar // \ // +---- homemadecar
We then create a method to display all info about a car.
public static void displayCar(Car myCar)
Here we might want to print if the car has a stereo:
if (myCar is musiCar) { if (((musiCar)myCar).hasStereo) Console.WriteLine(" - has a stereo"); else Console.WriteLine(" - has no stereo"); // ... }
Now: what if it is some other class that also might have a stereo. We want to print that aswell. This is the interesting part, we use GetField on the type of car we are dealing with.
if (!(myCar is musiCar)) { try { Type T = myCar.GetType(); FieldInfo field = T.GetField("hasStereo"); if ((bool)field.GetValue(myCar)) Console.WriteLine(" - has a stereo :)"); else Console.WriteLine(" - has no stereo :)"); } catch (Exception ex) { Console.WriteLine(" the 'hasStereo' of this car was not a bool..."); Console.WriteLine(" {0}", ex.Message); } }
Of course we want to wrap this around a try catch since we really do not know what the car looks like.
I made the main function like this
static void Main(string[] args) { oldCar c1 = new oldCar(); c1.age = 25; c1.color = "beige"; c1.hasStereo = false; c1.miles = int.MaxValue / 2; c1.nickname = "ugly betty"; niceCar c2 = new niceCar(); c2.color = "light blue metallic"; c2.hasMP314Player = true; c2.hasStereo = c2.hasMP314Player; c2.miles = 1337; c2.nickname = "Turing the Tempest"; homeMadeCar c3 = new homeMadeCar(); c3.color = "black"; c3.hasStereo = true; c3.isEpa = true; c3.miles = 555; c3.nickname = "KB::P_WAGON"; Console.WriteLine(); Console.WriteLine("CAR 1"); displayCar(c1); Console.WriteLine(); Console.WriteLine("CAR 2"); displayCar(c2); Console.WriteLine(); Console.WriteLine("\"CAR\" 3"); displayCar(c3); }
The output
>epatraktor CAR 1 The beige car... - is called 'ugly betty' - has run for '1073741823' miles - has no stereo - is 25 years old CAR 2 The light blue metallic car... - is called 'Turing the Tempest' - has run for '1337' miles - has a stereo - has an MP314 player "CAR" 3 The black car... - is called 'KB::P_WAGON' - has run for '555' miles - this is in fact an epatraktor. - has a stereo :)
See Also
This page belongs in Kategori Programmering.