何时在重载转换运算符时使用关键字“implicit”或“explicit”?

时间:2015-01-06 13:24:20

标签: c# type-conversion overloading

我正在学习C#。在重载转换运算符时,本教程不清楚何时使用关键字implicitexplicit

它提供的示例如下:

  

Class1包含int类型的字段且Class2包含double类型的字段时,我们应该定义从Class2到{的显式转换{1}},以及从Class1Class1的隐式转换。

本教程没有说明如果我使用错误的关键字会发生什么。

但如果Class2包含复杂的子类且Class1包含不同的子类,我应该在Class2implicit之间使用哪个关键字?谁能给出明确的解释?非常感谢。

1 个答案:

答案 0 :(得分:1)

  

隐式转化:不需要特殊语法,因为   转换是类型安全的,不会丢失任何数据。例子包括   从较小到较大的整数类型转换,和转换   从派生类到基类

     

明确转换(强制转换):

     

显式转换需要强制转换运算符。铸造是必需的   信息可能会在转换或转换时丢失   由于其他原因可能不会成功。典型的例子包括数字   转换为精度较低或范围较小的类型,和   将基类实例转换为派生类。

检查此说明中的粗体文字。以下是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;