简体   繁体   English

在C#中从基本类型转换为派生类型

[英]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. 如果使用as运算符,并且目标类型是引用类型,则在无法执行强制转换的情况下将获得null。

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).

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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