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

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

问题描述

我总是好奇。



为什么这样工作:

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

但这不是:

  double Number =(double)TextBox1.Text; 


解决方案

/ p>

当我在IDE中输入这行代码时:

  double Number =(double)TextBox1.Text; 

为什么编译器不能隐式地将它转换为:

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

这里的问题是您正在使用 explicit cast 。你真正对编译器说的是...



即使我声明这个内存块为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天全站免登陆