This sounds like pretty much complexity for the problem domain: If I got you
right, you got the conversion code 6 times (Kg -> g, Kg -> mg, g -> Kg, g ->
mg, mg -> Kg, mg -> g) in 3 different classes. Adding more metrics (like
pounds, etc) would result in an explosion of conversion functions. (Not even
mentioning addition, subtraction...)
I'd suggest something simple like:
public abstract class Weight
{
static double Kilogram(double kg) { return kg * 1000; }
static double Gram(double g) { return g; }
static double Milligram(double mg) { return mg / 1000; }
}
Thus keeping all internal data in one fixed format.
If you want to add type-safety (e.g. to prevent adding weights to lengths),
you could use a value-type like:
public struct Weight
{
private double val;
private Weight(double v) { val = v; }
public static Weight Kilogram(double kg) { return new Weight(kg * 1000); }
public static Weight Gram(double g) { return new Weight(g); }
public static Weight Milligram(double mg) { return new Weight(mg /
1000); }
// You could also declare the accessor functions as properties, if you
name them differently
public double Kilogram() { return val/1000; }
public double Gram() { return val; }
public double Milligram() { return val*1000; }
public static Weight operator + (Weight l, Weight r)
{ return new Weight(l.val + r.val); }
// other math operations
// ToString override, for kg/g/mg formatting
// ...
}
So you could write:
Weight x = Weight.Kilogram(5)+Weight.Gram(500);
double y = x.Milligram();
However, you should make performance tests to decide whether the added type
safety is worth the performance penalty.
Niki
"David" <da*******@hotmail.com> wrote in
news:%2****************@TK2MSFTNGP09.phx.gbl...
i've abstract class Weight
public abstract class Weight
{
public int Quantity; // how much it weigths
}
and then i created 3 derived classes: Kilogram, Gram and Milligram
in each of them i created an implicit operator to convert from one to
another...
it works fine...
then in each of them is 3 constructors, one takes "Quantity" from int
value, and two others from other clsses, like for kilogram it would be milligram
and gram.
then i tryed to overload operator + for each of them...
and here troubles begin...
C# can't choose wich operator overload to use +, implicit, constructor...
a mess, i should say...
how this can be solved
thnx...