C# 转换为字符串与调用 ToString
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1565100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting to string versus calling ToString
提问by Embedd_Khurja
object obj = "Hello";
string str1 = (string)obj;
string str2 = obj.ToString();
What is the difference between (string)obj
and obj.ToString()
?
(string)obj
和 和有obj.ToString()
什么区别?
采纳答案by Mac
(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.
(string)obj
转换obj
为string
.obj
必须已经是一个string
才能成功。obj.ToString()
obj
通过调用ToString()
方法获取 的字符串表示。这是obj
本身的时候obj
是一个string
。这(应该)永远不会抛出异常。
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 boxingever occurs.
回答by ChrisF
At the most basic level:
在最基本的层面上:
(string)obj
will attempt to cast obj
to a string
and will fail if there's no valid conversion.
(string)obj
将尝试强制转换obj
为 astring
并且如果没有有效的转换将会失败。
obj.ToString()
will return a string
that the designer of obj
has decided represents that object. By default it returns the class name of obj
.
obj.ToString()
将返回string
设计者obj
已决定代表该对象的一个。默认情况下,它返回 的类名obj
。
回答by Guillaume
(string)obj cast the object and will fail if obj is not null and not a string.
(string)obj 投射对象,如果 obj 不为 null 且不是字符串,则将失败。
obj.ToString() converts obj to a string (even if it is not a string), it will fail is obj is null as it's a method call.
obj.ToString() 将 obj 转换为字符串(即使它不是字符串),如果 obj 为空,它会失败,因为它是一个方法调用。
回答by amr osama
ToString() is object class method (the main parent class in .net) which can be overloaded in your class which inherits from object class even if you didn't inherited from it.
ToString() 是对象类方法(.net 中的主要父类),它可以在从对象类继承的类中重载,即使您没有从它继承。
(string) is casting which can be implemented in the class it self, the string class so you don't have ability on it.
(string) 正在转换,它可以在它自己的类中实现,字符串类所以你没有能力。
回答by Nick Masao
If its any help, you could use the 'as' operator which is similar to the cast but returns null instead of an exception on any conversion failure.
如果有任何帮助,您可以使用类似于强制转换的“as”运算符,但在任何转换失败时返回 null 而不是异常。
string str3 = obj as string;