微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

参见英文答案 > When must we use implicit and explicit operators in C#?                                    2个
我正在学习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
@R_9_4045@ion 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;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐