简体   繁体   中英

Casting from base type to derived type in c#

So I know you can't cast from base type to derived type because an Animal might not be a Cat etc etc.

Given that, can you suggest a better way to implement this code, and avoid having to repeat the operator declaration and instantiate new objects?

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 };
    }
}

So I know you can't cast from base type to derived type because an Animal might not be a Cat etc etc.

Wrong.

You can, if the object is not of the target type you'll get an exception.

If you use the as operator and the target type is a reference type you'll get null if the cast cannot be performed.

So

Animal d = new Dog();

var c = (Cat)d;   // Will throw

var c1 = d as Cat; // Will return null (assuming Dog is a reference type).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM