Extending classes and overriding properties in a C# .NET constructor
I'm a PHP programmer by default, and I need a little help with a C# .NET (Micro Frameworks, but that doesn't matter here) project.
Basically, I have a class that allows for control of an RC car or airplane speed controller. The class is already written, but I need a way to import settings into the class, since diffident electric speed controllers require different settings.
My ideal set up would be something like this:
SpeedController esc = new SpeedController(SpeedControllers.TRAXXAS_XL5);
I know how the constructor and all that work, but how do I configure the SpeedControllers.TRAXXAS_XL5 part? I 开发者_JAVA百科would create a base class (Speedcontrollers) and then a class that extends it, overriding the default values, correct?
Can someone direct me to a tutorial on what I am talking about or a small code snippet of a child class overriding properties in a parent class?
I'll just take an example using a hypothetical MaxSpeed
the conroller might have.
abstract class SpeedControllers {
public abstract int MaxSpeed { get; }
public class TRAXXAS_XL5 : SpeedControllers{
public override int MaxSpeed {
get {
return 30;
}
}
}
}
Then in your SpeedController constructor
class SpeedController {
readonly SpeedControllers properties;
public SpeedController(SpeedControllers properties) {
this.properties = properties;
}
public int MaxSpeed {
get {
return properties.MaxSpeed;
}
}
}
Call it with new SpeedController(new SpeedControllers.TRAXXAS_XL5())
IMO, best way to do that would be something like this:
public struct SpeedControllers {
int speed;
int etc;
public SpeedControllers(int s, int e) {
speed = s;
etc = e;
}
public const SpeedControllers TRAXXAS_XL5 = new SpeedControllers(123, 345);
public const SpeedControllers WHATEVER = new SpeedControllers(456, 789);
}
And, have the SpeedController
constructor read the values out of the struct. Obviously, add/customize the fields as necessary.
DISCLAIMER: I haven't run this through the compiler, only through my brain. Do not attempt to fly an actual airplane with this as is ;)
If SpeedControllers.TRAXXAS_XL5 is nothing but configuration data (i.e., all numeric values) then I wouldn't consider this an optimal example of derived classes.
Yes, you can create a base class (SpeedController) which contains the properties and perhaps default values. Then you could create derived classes that override.
Instead, what Mike Caron has demonstrated is using the same class and simply using initialization of the data to create the various specialized instances of the controller class. I would recommend something like that (perhaps loading the values from an external file if you want to make it easy to configure).
精彩评论