string s = (string)o; // 1
Throws InvalidCastException if o
is not a string
.
(如果o
不是string
则抛出InvalidCastException 。)
Otherwise, assigns o
to s
, even if o
is null
. (否则,将o
分配给s
,即使o
为null
。)
string s = o as string; // 2
Assigns null
to s
if o
is not a string
or if o
is null
.
(分配null
到s
,如果o
是不是一个string
,或者o
为null
。)
For this reason, you cannot use it with value types (the operator could never return null
in that case). (因此,您不能将其与值类型一起使用(在这种情况下,运算符永远不会返回null
)。)
Otherwise, assigns o
to s
. (否则,将o
分配给s
。)
string s = o.ToString(); // 3
Causes a NullReferenceException if o
is null
.
(如果o
为null
则导致NullReferenceException 。)
Assigns whatever o.ToString()
returns to s
, no matter what type o
is. (将o.ToString()
返回的值o.ToString()
s
,无论o
是什么类型。)
Use 1 for most conversions - it's simple and straightforward.
(大多数转换使用1-简单明了。)
I tend to almost never use 2 since if something is not the right type, I usually expect an exception to occur. (我倾向于几乎从不使用2,因为如果某些类型不正确,我通常希望发生异常。)
I have only seen a need for this return-null type of functionality with badly designed libraries which use error codes (eg return null = error, instead of using exceptions). (我只看到这种返回null类型的功能需要使用错误代码(例如,返回null =错误,而不是使用异常)的错误设计的库。)
3 is not a cast and is just a method invocation.
(3不是强制转换,而只是方法调用。)
Use it for when you need the string representation of a non-string object. (在需要非字符串对象的字符串表示形式时使用它。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…