重载转换运算符时何时使用关键字 "implicit" 或 "explicit"?
When to use keyword "implicit" or "explicit" when overloading conversion operators?
我正在学习 C#。本教程没有明确说明在重载转换运算符时何时使用关键字 implicit
或 explicit
。
它提供的例子是这样的:
When Class1
contains a field of type int
and Class2
contains a field of type double
, we should define an explicit conversion from Class2
to Class1
, and an implicit conversion from Class1
to Class2
.
教程没有说如果我使用错误的关键字会发生什么。
但是如果Class1
包含一个复杂的子类而Class2
包含一个不同的子类,我应该在implicit
和explicit
之间使用哪个关键字?任何人都可以给出明确的解释吗?非常感谢。
Implicit conversions: No special syntax is required because the
conversion is type safe and no data will be lost. Examples include
conversions from smaller to larger integral types, and conversions
from derived classes to base classes.
Explicit conversions (casts):
Explicit conversions require a cast operator. Casting is required when
information might be lost in the conversion, or when the conversion
might not succeed for other reasons. Typical examples include numeric
conversion to a type that has less precision or a smaller range, and
conversion of a base-class instance to a derived class.
检查此解释中的粗体文本。这是MSDN
中的详细文章
这是一个小代码示例:
// Create a new derived type.
Giraffe g = new Giraffe();
// Implicit conversion to base type is safe.
Animal a = g;
// Explicit conversion is required to cast back
// to derived type. Note: This will compile but will
// throw an exception at run time if the right-side
// object is not in fact a Giraffe.
Giraffe g2 = (Giraffe) a;
我正在学习 C#。本教程没有明确说明在重载转换运算符时何时使用关键字 implicit
或 explicit
。
它提供的例子是这样的:
When
Class1
contains a field of typeint
andClass2
contains a field of typedouble
, we should define an explicit conversion fromClass2
toClass1
, and an implicit conversion fromClass1
toClass2
.
教程没有说如果我使用错误的关键字会发生什么。
但是如果Class1
包含一个复杂的子类而Class2
包含一个不同的子类,我应该在implicit
和explicit
之间使用哪个关键字?任何人都可以给出明确的解释吗?非常感谢。
Implicit conversions: No special syntax is required because the conversion is type safe and no data will be lost. Examples include conversions from smaller to larger integral types, and conversions from derived classes to base classes.
Explicit conversions (casts):
Explicit conversions require a cast operator. Casting is required when information might be lost in the conversion, or when the conversion might not succeed for other reasons. Typical examples include numeric conversion to a type that has less precision or a smaller range, and conversion of a base-class instance to a derived class.
检查此解释中的粗体文本。这是MSDN
中的详细文章这是一个小代码示例:
// Create a new derived type.
Giraffe g = new Giraffe();
// Implicit conversion to base type is safe.
Animal a = g;
// Explicit conversion is required to cast back
// to derived type. Note: This will compile but will
// throw an exception at run time if the right-side
// object is not in fact a Giraffe.
Giraffe g2 = (Giraffe) a;