铸造的差异 [英] differences in casting

查看:64
本文介绍了铸造的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么区别:

string myString = value.toString();



字符串myString =(字符串)值;



如果不同,您还可以提供示例吗?

解决方案

完全不同!

使用ToString时

  string  myString =  value  .toString(); 

您正在实现ToString的值层次结构中调用最高派生类中的方法,并且该方法返回值的字符串表示形式 - 并且.NET中的每个类都实现了Tostring,即使只是通过Object.ToString实现,它返回一个包含类名的字符串。



所以它的值是一个int,包含666:

< pre lang =c#> string myString = value .toString();

会给你一个字符串666。

如果value是一个DataGridView,那么你将得到一个包含System.Windows.Forms.DataGridView的字符串,因为DataGridView本身并没有实现TopString,并且依赖在默认的Object.ToString方法上。



Casting是一个不同的过程:它试图返回一个你要转换的类型的值。这两种类型不兼容,那么你将得到一个编译错误无法将类型'abc'转换为'string'或运行时异常无法将'abc'类型的对象转换为'System.String'类型。 如果代码将编译。转换不会更改值,它只是将其作为不同类的实例返回。

例如:

  int  i =  666 ; 
string s =( string )i;

会给你编译器错误,因为您不能将整数视为字符串,并且

  int  i = < span class =code-digit> 666 ; 
object o = i;
string s =( string )o;

赢了; t给你一个编译错误,因为你可以将 某些 对象转换为字符串,但是会给你一个运行时错误,因为你仍然不能将整数视为一个字符串!



另外看看关键字 - 它们允许您测试值以查看演员是否有效。


What is the difference between:
string myString = value.toString();
And
string myString = (string)value;

Can you also provide examples please if different.

解决方案

Totally different!
When you use ToString

string myString = value.toString(); 

You are calling a method in the highest derived class in the values hierarchy which implements ToString, and that method returns a string representation of the value - and every class in .NET implements Tostring, even if only via the Object.ToString implementation which returns a string containing the name of the class.

So it value is an int, containing 666:

string myString = value.toString();

will give you a string "666".
If value is a DataGridView, then you will get a string containing "System.Windows.Forms.DataGridView" because DataGridView does not implement TopString itself, and relies on the default Object.ToString method.

Casting is a different process: it tries to return a value that is the type that you are casting to. It the two types are not compatible, then you will get a compilation error "Cannot convert type 'abc' to 'string'" or a run time exception "Unable to cast object of type 'abc' to type 'System.String'." if it code will compile. Casting does not change the value, it just returns it as an instance of a different class.
For example:

int i = 666;
string s = (string)i;

Will give you a compiler error because you can't treat an integer as a string, and

int i = 666;
object o = i;
string s = (string)o;

Won;t give you a compilation error, because you can convert some objects to a string, but will give you a run time error because you still can't treat an integer as a string!

Also have a look at the is and as keywords - they let you test values to see is a cast would work.


这篇关于铸造的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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