铸造字符串与调用toString [英] Casting to string versus calling ToString
本文介绍了铸造字符串与调用toString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
object obj = "Hello";
string str1 = (string)obj;
string str2 = obj.ToString();
什么是(字符串)OBJ 之间的区别>和 obj.ToString()
?
推荐答案
-
(串)OBJ
蒙上OBJ
到字符串
。OBJ
必须已经是字符串
此成功。 -
obj.ToString()
通过调用的 OBJ 的字符串表示.COM / EN-US /库/ system.object.tostring.aspx>的ToString()
方法。这是OBJ
本身时OBJ
是字符串
。这(应)永远不会抛出(S)异常。
(string)obj
castsobj
into astring
.obj
must already be astring
for this to succeed.obj.ToString()
gets a string representation ofobj
by calling theToString()
method. Which isobj
itself whenobj
is astring
. This (should) never throw(s) an exception.
因此,在特定的情况下,无论是等价的。
So in your specific case, both are equivalent.
注意字符串
是的引用类型(而不是一个值类型)。因此,它从对象继承,没有拳击有史以来发生。
Note that string
is a reference type (as opposed to a value type). As such, it inherits from object and no boxing ever occurs.
这篇关于铸造字符串与调用toString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文