在C#铸造/转换方法的区别 [英] Difference between casting/conversion methods in C#

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

问题描述

有很多方法可以施放/由什么区别那些之间的转换对象到另一个对象,如果没有什么区别,为什么有这么多的方式来实现的一件事?不是语言,损害?



假设obj对象为字符串。

  obj.ToString()
OBJ作为字符串
(串)OBJ
Convert.ToString(OBJ)


解决方案

您在这里做不同的事情:




  • obj.ToString() - 这是对调用toString()对象的方法。因为它是编程的对象返回一个字符串

  • OBJ为字符串 - 这是将对象转换为字符串,它可能会或可能不会失败(如果失败的尝试,结果是),不将引发异常

  • (串)目标文件 - 这是一个明确的投 OBJ 的类型字符串,你是在告诉 OBJ 是的一个字符串。如果 OBJ 是不是一个字符串类型,你会得到一个转换异常

  • Convert.ToString(OBJ) - 这是一个明确的调用Convert类返回 OBJ 的字符串表示。



有这些许多不同的方式获得字符串对象,因为每个人都是的不同的的而有细微的差别。是的,在许多情况下,返回字符串将是相同的,但是这不被保证。


there are many ways to cast/convert object to another by what the difference between those and if there is no difference why there are so many ways to achieve one thing? Isn't that damage to language?

let's say object obj to string.

obj.ToString()
obj as string
(string)obj
Convert.ToString(obj)

解决方案

You are doing different things here:

  • obj.ToString() - this is a call to the ToString() method of the object. The object returns a string as it was programmed to.
  • obj as string - this is an attempt to convert the object to a string, which may or may not fail (if it fails, the result is null), no exception will be thrown.
  • (string)obj - this is an explicit cast of obj to the type string, you are telling the compiler that obj is a string. If obj is not a string type, you will get a cast exception.
  • Convert.ToString(obj) - This is an explicit call to the Convert class to return a string representation of obj.

There are these many different ways to get a string from an object because each one is different and have subtle differences. Yes, in many cases the returned string will be the same, but this is not guaranteed.

这篇关于在C#铸造/转换方法的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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