为什么的ConvertTo的工作,但铸造在某些情况下会失败呢? [英] Why does ConvertTo work, but casting fail in some cases?

查看:177
本文介绍了为什么的ConvertTo的工作,但铸造在某些情况下会失败呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是好奇



为什么这项工作:

 双数= Convert.ToDouble(TextBox1.Text); 



但是,这并不:

 双数=(双)TextBox1.Text; 


解决方案

我想你问的是...



当我键入这行代码到IDE:

 双数=(双)TextBox1.Text; 



为什么不能编译器把它变成这个含蓄:

 双数= Convert.ToDouble(TextBox1.Text); 



这里的问题是,你正在使用的明确的转换。你是从字面上说给编译器...



尽管我宣布的内存这个块是X,我要你把它像一个Y的编译器是足够聪明,知道它是否可以做或没有。因为你正试图转换的内存块的以System.String,编译器知道有把它当作好像它是一个System.Double没有可能的方式。



静态转换方法编程出解析值并创造所需类型的存储器一个全新的值,而不是简单地使用相同的字节存储器好象有别的。


I was always curious.

Why does this work:

double Number = Convert.ToDouble(TextBox1.Text);

But this doesn't:

double Number = (double)TextBox1.Text;

解决方案

I think what you are asking is...

When I type this line of code into the IDE:

double Number = (double)TextBox1.Text;

Why can't the compiler turn it into this implicitly:

double Number = Convert.ToDouble(TextBox1.Text);

The issue here is that you are using an explicit cast. What you are literally saying to the compiler is...

Even though I declared this chunk of memory to be X, I want you to treat it like a Y. The compiler is smart enough to know if it can be done or not. Since the chunk of memory you are trying to convert is a System.String, the compiler knows that there is no possible way to treat it as if it were a System.Double.

The static Convert methods are programatically parsing a value out and creating a brand new value in memory of the desired type, not simply using the same bytes in memory as though there were something else.

这篇关于为什么的ConvertTo的工作,但铸造在某些情况下会失败呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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