[英]Casting from base type to derived type in c#
所以我知道你不能从基本类型转换为派生类型,因为动物可能不是猫等。
鉴于此,您能建议一种更好的方法来实现此代码,而不必重复操作符声明和实例化新对象吗?
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 };
}
}
所以我知道你不能从基本类型转换为派生类型,因为动物可能不是猫等。
错误。
如果对象不是目标类型,则可以得到异常。
如果使用as
运算符,并且目标类型是引用类型,则在无法执行强制转换的情况下将获得null。
所以
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.