什么是显性和隐性的类型转换之间的区别? [英] What is the difference between explicit and implicit type casts?

查看:243
本文介绍了什么是显性和隐性的类型转换之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请您解释之间的明确类型转换的区别?

Can you please explain the difference between explicit and implicit type casts?

推荐答案

这是一个有点棘手,因为投的语法在C#中实际上做了一系列的不同的的东西(投,原始转换的,定制转换等)

This is a little tricky because the "cast" syntax in C# actually does a range of different things (cast, primitive convert, bespoke convert, etc)

在隐式转换,这两者之间存在明显的性基准preserving转换:

In an implicit cast, there is an obvious reference-preserving conversion between the two:

List<int> l = new List<int>();
IList<int> il = l;

编译器可以证明这是安全距离静态分析(列表&LT; INT&GT; 始终是的IList&LT; INT&GT;

使用显式类型转换,无论你是在告诉编译器你知道更多比它 - 请相信我,但无论如何,检查

With an explicit cast, either you are telling the compiler that you know more than it does - "please believe me, but check anyway":

List<int> l = new List<int>();
IList<int> il = l;
List<int> l2 = (List<int>)il;

虽然这演员阵容的可能的,编译器将不接受全部 的IList&LT; INT&GT; 是实际上列表与LT; INT方式&gt; - 所以我们必须告诉它通过让它

Although this cast is possible, the compiler won't accept that all IList<int>s are actually List<int> - so we must tell it to let it by.


在一个隐含的原语转换(providedby语言规范),人们普遍认为,有一个安全,无风险,无损耗(警告:见乔恩的评论)转换:

In an implicit primitive conversion (providedby the language spec), it is generally assumed that there is a safe, non-risky, non-lossy (caveat: see Jon's comment) conversion:

int i = 1;
float f = i;

通过明确的原语转换,很可能转换的可能的丢失数据,或是非显而易见的:

With an explicit primitive conversion, it is likely that the conversion could lose data, or is non-obvious:

float f = 1;
int i = (int)f;



使用定制的运营商,所有的赌注都关闭,你不得不看的文档。它可能是一个参考播送,或者它可以是<青霉>任何的。它可以遵循原始的转换类似的规则(例如:小数),也可以随意做任何事情:

With bespoke operators, all bets are off, and you'd have to look at the documentation. It could be a reference-cast, or it could be anything. It may follow similar rules to primitive conversions (example: decimal), or it could do anything randomly:

XNamespace ns = "http://abc/def"; // implicit
XAttribute attrib = GetAttrib();
int i = (int)attrib; // explicit (extracts text from attrib value and
                     // parses to an int)

这两种运行自定义code是特定上下文的。

Both of these run custom code that is context-specific.

这篇关于什么是显性和隐性的类型转换之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆