问题描述
考虑以下代码:
void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}
这三种类型的施法有什么区别(好吧,第三种不是施法,但你明白了).应该首选哪一个?
What is the difference between the three types of casting (okay, the 3rd one is not a casting, but you get the intent). Which one should be preferred?
推荐答案
string s = (string)o; // 1
如果 o
是,则抛出 InvalidCastException不是字符串
.否则,将 o
分配给 s
,即使 o
为 null
.
Throws InvalidCastException if o
is not a string
. Otherwise, assigns o
to s
, even if o
is null
.
string s = o as string; // 2
如果 o
不是 string
或者如果 o
则将 null
分配给 s
> 是 null
.因此,您不能将它与值类型一起使用(在这种情况下,运算符永远不会返回 null
).否则,将 o
分配给 s
.
Assigns null
to s
if o
is not a string
or if o
is null
. For this reason, you cannot use it with value types (the operator could never return null
in that case). Otherwise, assigns o
to s
.
string s = o.ToString(); // 3
如果 o
会导致 NullReferenceException是 null
.将任何 o.ToString()
返回的内容分配给 s
,无论 o
是什么类型.
Causes a NullReferenceException if o
is null
. Assigns whatever o.ToString()
returns to s
, no matter what type o
is.
对大多数转换使用 1 - 它简单明了.我几乎从不使用 2 ,因为如果某些类型不正确,我通常希望会发生异常.我只看到使用错误代码(例如返回 null = 错误,而不是使用异常)的糟糕设计的库需要这种返回 null 类型的功能.
Use 1 for most conversions - it's simple and straightforward. I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (e.g. return null = error, instead of using exceptions).
3 不是强制转换,只是一个方法调用.当您需要非字符串对象的字符串表示时使用它.
3 is not a cast and is just a method invocation. Use it for when you need the string representation of a non-string object.
这篇关于直接铸造与'as'运营商?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!