简体   繁体   中英

Is there a difference between the ToString method and casting to string?

object o;

o.ToString()(string) o之间有什么区别吗?

There is a difference, yes. Every object has a ToString method, but not every object can be cast to a string.

int i = 10;
string s1 = i.ToString(); // OK
string s2 = (string)i;    // Compile error.

object o = 10;
string s3 = o.ToString(); // OK
string s4 = (string)o;    // Runtime error.

当对象为nullToString()引发异常, (string)转换不为null

object.ToString() will convert the object into a string. If object has null value then it will throw an exception because no null value has ToString() method.

Whereas (string)object is a unboxing process of reference type to value type. Here an object value is copying into new instance of string type. If that object is null, it will assign null value.

如果您是从对象到字符串的安全转换对象,请使用:

string s = Convert.ToString(o);

Yes they both are very different.

string anObjectString = (string)anObject; is a Type cast or a Type conversion would only be successful if the type conversion is a valid one

ToString() is a method available to all the object(s) in the Framework. It is a virtual method where the default implementation returns you the Type name of the object.

We're comparing apples to oranges here..

Yes, ToString() is a method which every type implements (since every type inherits from System.Object which implements the method). Certain types may override this method to provide their own custom overriding implementations. A call to ToString() should always succeed and return a string instance (although it may be null for some implementations).

var x = new AnyArbitraryObjectType();
var y = x.ToString(); // will always succeed (if ToString has not been overridden, or if it has been overridden properly)

A cast is the conversion of a given object reference to a reference typed as string. If the reference being cast is not a string, then the cast will fail.

var a = "hello";
var b = 5;

var x = (string)a; // will succeed
var y = (string)b; // will fail with InvalidCastException

basically ToString() is a function that returns a string that represents the object you applied it on.

string as a type is like an int - a primitive (in c# its an object)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM