加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 22:10:34 所属栏目:百科 来源:网络整理
导读:参见英文答案 When must we use implicit and explicit operators in C#?????????????????????????????????????2个 我正在学习C#.在重载转换运算符时,本教程不清楚何时使用关键字implicit或explicit. 它提供的示例如下: When Class1 contains a field of ty
参见英文答案 > 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
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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读