什么是正常的类型转换,并使用“AS”关键字的区别关键字、区别、正常、类型

2023-09-03 00:32:58 作者:光阴荏苒,唯有珍惜

可能显示的文件:   直接铸造VS'为'经营者?   铸造:(NEWTYPE)与对象为NE​​WTYPE

Possible Duplicates: Direct casting vs 'as' operator? Casting: (NewType) vs. Object as NewType

什么是正常的类型转换,并使用AS之间的区别关键字?

What is difference between normal typecasting and using "AS" keyword?

推荐答案

使用将无法正常如果对象是错误的类型,以及所产生的价值将是无效,在一个正常的投会抛出一个InvalidCastException:

Using as will fail gracefully if the object is the wrong type, and the resulting value will be null, where a normal cast would throw an InvalidCastException:

object x = new object();
string y = x as string; // y == null
string z = (string)x; // InvalidCastException