cdh*_*wie 11
如果要转换的对象不是所请求的类型,则直接转换将失败.一个as-cast反而会返回null.例如:
object obj = new object();
string str = (string)obj; // Throws ClassCastException
Run Code Online (Sandbox Code Playgroud)
然而:
object obj = new object();
string str = obj as string; // Sets str to null
Run Code Online (Sandbox Code Playgroud)
当要转换的对象属于您要转换的类型时,任一语法的结果都相同:对象已成功转换.
请特别注意,您应该避免使用"as-and-invoke"模式:
(something as SomeType).Foo();
Run Code Online (Sandbox Code Playgroud)
因为如果转换失败,您将抛出NullReferenceException而不是ClassCastException.这可能会导致你追逐something无效的原因,而实际上并非如此!更丑陋,但更好的代码
((SomeType)something).Foo();
Run Code Online (Sandbox Code Playgroud)
当引用的对象something无法转换SomeType为时,将抛出ClassCastException; 如果something为null ,则抛出NullReferenceException .
| 归档时间: |
|
| 查看次数: |
196 次 |
| 最近记录: |