所以我知道你不能从基类型转换为派生类型,因为 Animal 可能不是 Cat 等。
鉴于此,您能否建议一种更好的方法来实现此代码,并避免重复操作符声明和实例化新对象?
class scientific_number
{
public decimal value;
public int precision;
public static implicit operator scientific_number(decimal value)
{
return new scientific_number() { value = value, precision = 0 };
}
public static implicit operator scientific_number(int value)
{
return new scientific_number() { value = (decimal)value, precision = 0 };
}
public static implicit operator scientific_number(double value)
{
return new scientific_number() { value = (decimal)value, precision = 0 };
}
}
class amu : scientific_number
{
public static implicit operator amu(scientific_number scientific_number)
{
return new amu() { value = scientific_number.value, precision = scientific_number.precision };
}
public static implicit operator amu(decimal value)
{
return new amu() { value = value, precision = 0 };
}
public static implicit operator amu(int value)
{
return new amu() { value = (decimal)value, precision = 0 };
}
public static implicit operator amu(double value)
{
return new amu() { value = (decimal)value, precision = 0 };
}
public kg ToEarthKg()
{
return this.value / 0.00000000000000000000000000166053886;
}
}
class kg : scientific_number
{
public static implicit operator kg(scientific_number scientific_number)
{
return new kg() { value = scientific_number.value, precision = scientific_number.precision };
}
public static implicit operator kg(decimal value)
{
return new kg() { value = value, precision = 0 };
}
public static implicit operator kg(int value)
{
return new kg() { value = (decimal)value, precision = 0 };
}
public static implicit operator kg(double value)
{
return new kg() { value = (decimal)value, precision = 0 };
}
}