.ToString 和“as string”之间的区别在 C# 中
使用以下两个语句有什么区别?在我看来,第一个“as string”是类型转换,而第二个 ToString 是对将输入转换为字符串的方法的实际调用?只是寻找一些见解(如果有的话)。
Page.Theme = Session["SessionTheme"] as string;
Page.Theme = Session["SessionTheme"].ToString();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
如果
Session["SessionTheme"]
不是string
,as string
将返回null
。.ToString()
将尝试通过调用对象的ToString()
方法将任何其他类型转换为字符串。对于大多数内置类型,这将返回转换为字符串的对象,但对于没有特定.ToString()
方法的自定义类型,它将返回对象类型的名称。另一件需要记住的重要事情是,如果对象为 null,调用 .ToString() 会抛出异常,但 as string 会抛出异常只需返回
null
。If
Session["SessionTheme"]
is not astring
,as string
will returnnull
..ToString()
will try to convert any other type to string by calling the object'sToString()
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.Another important thing to keep in mind is that if the object is
null
, calling.ToString()
will throw an exception, butas string
will simply returnnull
.as
关键字基本上将使用 MSIL 操作码isinst
检查对象是否是该类型的实例。如果是,则返回对该对象的引用,否则返回空引用。正如许多人所说,它并不尝试执行这样的转换 - 这意味着某种异常处理。并非如此。
ToString()
,只需调用对象的ToString()
方法,该方法可以是由类实现的自定义方法(对于大多数内置类型执行到字符串的转换) -或者如果没有提供,则为基类object
的一个,返回类型信息。The
as
keyword will basically check whether the objectis
an instance of the type, using MSIL opcodeisinst
under the hood. If it is, it returns the reference to the object, else a null reference.It does not, as many say, attempt to perform a cast as such - which implies some kind of exception handling. Not so.
ToString()
, simply calls the object'sToString()
method, either a custom one implemented by the class (which for most in-built types performs a conversion to string) - or if none provided, the base classobject
's one, returning type info.我稍微扩展了 Philippe Leybaert 已接受的答案,因为虽然我找到了比较其中三个的资源,但我从未找到比较所有四个的解释。
(string)obj
obj as string
obj.ToString()
Convert.ToString(obj)
从这些结果我们可以看到,当
obj
为字符串或 null 时,(string)obj
和obj as string
的行为方式相同;否则(string)obj
将抛出无效的转换异常,并且obj as string
将仅返回 null。obj.ToString()
和
Convert.ToString(obj)
的行为也彼此相同,除非obj
为 null,在这种情况下obj.ToString()
将引发空引用异常,并且Convert.ToString(obj)
将返回空字符串。所以这里是我的建议:
(string)obj
效果最好obj as string
效果最好您不想引发任何异常,也不希望非字符串的字符串表示形式obj.ToString()
如果您想引发 null 异常Convert.ToString(如果您不想引发任何异常并想要非字符串的字符串表示形式,则 obj)
效果最好编辑:我发现
Convert.ToString()
实际上会处理null
根据重载的不同而有所不同,因此在本例中变量被声明为object
实际上很重要。如果您对string
变量(null
)调用Convert.ToString()
,那么它将返回null
而不是 <代码>字符串.空。I'm extending Philippe Leybaert's accepted answer a bit because while I have found resources comparing three of these, I've never found an explanation that compares all four.
(string)obj
obj as string
obj.ToString()
Convert.ToString(obj)
From these results we can see that
(string)obj
andobj as string
behave the same way as each other whenobj
is a string or null; otherwise(string)obj
will throw an invalid cast exception andobj as string
will just return null.obj.ToString()
and
Convert.ToString(obj)
also behave the same way as each other except whenobj
is null, in which caseobj.ToString()
will throw a null reference exception andConvert.ToString(obj)
will return an empty string.So here are my recommendations:
(string)obj
works best if you want to throw exceptions for types that can't be assigned to a string variableobj as string
works best if you don't want to throw any exceptions and also don't want string representations of non-stringsobj.ToString()
works best if you want to throw exceptions for nullConvert.ToString(obj)
works best if you don't want to throw any exceptions and want string representations of non-stringsEDIT: I've discovered that
Convert.ToString()
actually treatsnull
differently depending on the overload, so it actually matters that the variable was declared as anobject
in this example. If you callConvert.ToString()
on astring
variable that'snull
then it will returnnull
instead ofstring.Empty
.尝试转换为字符串
,同时
调用
ToString()
方法,该方法实际上可以是任何内容。此方法不进行强制转换,它应该返回该对象的字符串表示形式。tries to cast to a string
whereas
calls the
ToString()
method, which can be anything really. This method doesn't cast, it should return a string representation of this object.首先,“any-object as string”和“any-object.ToString()”在各自的上下文中是完全不同的东西。
1) 这会将任何对象转换为字符串类型,如果任何对象不可转换为字符串,则此语句将返回 null 且不会引发任何异常。
2) 这是一个编译器服务。
3)这对于除字符串之外的任何其他类型都非常有效,例如:您可以将其作为任何对象(例如 Employee),其中 Employee 是在您的库中定义的类。
1) 这将从类型定义中调用任何对象的 ToString()。由于 System.Object 定义了 ToString() 方法,.Net 框架中的任何类都具有可覆盖的 ToString() 方法。程序员将重写任意对象类或结构定义中的 ToString(),并编写根据任意对象的责任和角色返回任意对象的合适字符串表示形式的代码。
2)就像您可以定义一个 Employee 类并覆盖 ToString() 方法,该方法可能返回 Employee 对象的字符串表示形式为 "FIRSTNAME - LASTNAME, EMP-CDOE" 。
请注意,在这种情况下,程序员可以控制 ToString(),并且它与强制转换或类型转换无关。
First of all "any-object as string" and "any-object.ToString()" are completely different things in terms of their respective context.
1) This will cast any-object as string type and if any-object is not castable to string then this statement will return null without throwing any exception.
2) This is a compiler-service.
3) This works pretty much well for any other type other than string, ex: you can do it as any-object as Employee, where Employee is a class defined in your library.
1) This will call ToString() of any-object from type-defination. Since System.Object defines ToString() method any class in .Net framework has ToString() method available for over-riding. The programmer will over-ride the ToString() in any-object class or struct defination and will write the code that return suitable string representation of any-object according to responsibility and role played by any-object.
2) Like you can define a class Employee and over-ride ToString() method which may return Employee object's string representation as "FIRSTNAME - LASTNAME, EMP-CDOE" .
Note that the programmer has control over ToString() in this case and it has got nothing to do with casting or type-conversion.
为了进一步混淆问题,C# 6.0 引入了 空条件运算符。所以现在也可以写成:
它将返回 null 或 ToString() 的结果而不抛出异常。
To confuse the matter further, C# 6.0 has introduced the null-conditional operator. So now this can also be written as:
Which will return either null or the result from ToString() without throwing an exception.
as string
检查对象是否为字符串。如果它不是 null 则返回。对
ToString()
的调用确实会调用对象上的ToString()
方法。The
as string
check is the object is a string. If it isn't a null it returned.The call to
ToString()
will indeed call theToString()
method on the object.如果类是字符串或从字符串派生,第一个将类作为字符串返回(如果不成功则返回 null)。
第二个调用类上的 ToString() 方法。
The first one returns the class as a string if the class is a string or derived from a string (returns null if unsuccessful).
The second invokes the ToString() method on the class.
实际上,编写上述代码的最佳方法是执行以下操作:
这样您几乎可以肯定它不会抛出 NullReferenceException。
Actually the best way of writing the code above is to do the following:
That way you're almost certain that it won't cast a NullReferenceException.