我正在学习C#。在重载转换运算符时,本教程不清楚何时使用关键字implicit
或explicit
。
它提供的示例如下:
当
Class1
包含int
类型的字段且Class2
包含double
类型的字段时,我们应该定义从Class2
到{的显式转换{1}},以及从Class1
到Class1
的隐式转换。
本教程没有说明如果我使用错误的关键字会发生什么。
但如果Class2
包含复杂的子类且Class1
包含不同的子类,我应该在Class2
和implicit
之间使用哪个关键字?谁能给出明确的解释?非常感谢。
答案 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;