String casts in .NET

后端 未结 9 1049
死守一世寂寞
死守一世寂寞 2021-02-15 02:21

Why is there so may ways to convert to a string in .net? The ways I have seen are .ToString, Convert.ToString() and (string). What is the Difference.

9条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-15 03:00

    • .ToString() can be called from any object. However, if the type you call it on doesn't have a good implementation the default is to return the type name rather than something meaningful about the instance of that type. This method is inherited from the base Object type, and you can overload it in your own types to do whatever you want.

    • (string) is a cast, not a function call. You should only use this if the object you need already is a string in some sense, or if you know there is a good implicit conversion available (like from int). This will throw an exception is the object cannot be converted (including when the object is null)

    • as string is another way to write (string), but it differs in that it returns null rather than throwing an exception if the cast fails.

    • Convert.ToString() attempts to actually convert the argument into a string. This is the best option if you don't really know much about the argument. It can be slow because it has to do a lot of extra work to determine what kind of results to return, but that same work also makes it the most robust option when you don't know very much about the argument. If nothing else is available, it will fall back to calling the argument's .ToString() method.

    • String.Format The string class' .Format method can also be used to convert certain types to strings, with the additional advantage that you have some control over what the resulting string will look like.

    • Serialization This is a little more complicated, but .Net includes a couple different mechanisms for converting objects into a representation that can be safely stored and re-loaded from disk or other streaming mechanism. That includes a binary formatter, but most often involves converting to a string in some format or other (often xml). Serialization is appropriate when you want to later convert the your string back into it's originating type, or if you want a complete representation of a complex type.

提交回复
热议问题