的ToString和&QUOT之间的差异,如串QUOT;在C#中 [英] Difference between .ToString and "as string" in C#

查看:138
本文介绍了的ToString和&QUOT之间的差异,如串QUOT;在C#中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是使用以下两种语句之间的区别?在我看来,那首为串是一个类型转换,而第二的ToString是与输入转换为字符串的方法的实际调用? 。只是在寻找一些见解,如果任何

  Page.Theme =会话[SessionTheme]作为字符串; 
Page.Theme =会话[SessionTheme]的ToString()。


解决方案

如果会话[SessionTheme]是不是字符串为串将返回null。



的ToString()将尝试通过调用该对象的的ToString()方法的任何其他类型的字符串转换。对于大多数内置类型,这将返回该对象转换为字符串,但对于自定义类型没有特定的ToString()方法,这将返回该对象的类型的名称。



 像O1 =somestring; 
对象02 = 1;

字符串s = 01的字符串; //返回somestring
字符串s = 02为串; //返回null
字符串s = o2.ToString(); //返回1

要记住另一个重要的事情是,如果对象为空,调用的ToString()将抛出一个异常,而是为串只会返回null。


What is the difference between using the two following statements? It appears to me that the first "as string" is a type cast, while the second ToString is an actual call to a method that converts the input to a string? Just looking for some insight if any.

Page.Theme = Session["SessionTheme"] as string;
Page.Theme = Session["SessionTheme"].ToString();

解决方案

if Session["SessionTheme"] is not a string, "as string" will return null.

.ToString() will try to convert any other type to string by calling the object's .ToString() method. For most built-in types this will return the object converted to a string, but for custom types without a specific .ToString() method, it will return the name of the type of the object.

object o1 = "somestring";
object o2 = 1;

string s = o1 as string; // returns "somestring"
string s = o2 as string; // returns null
string s = o2.ToString(); // returns "1"

Another important thing to keep in mind is that if the object is null, calling .ToString() will throw an exception, but "as string" will simply return null.

这篇关于的ToString和&QUOT之间的差异,如串QUOT;在C#中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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