What is the difference between “object as type” and “((type)object)”?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Direct casting vs 'as' operator?
Casting vs using the 'as' keyword in the CLR
1 2 | object myObject ="Hello world."; var myString = myObject as string; |
1 2 | object myObject ="Hello world."; var myString = (string)myObject; |
我已经看到两种方式都进行了类型转换。 有什么不同?
如果失败,"as"会将结果设置为
如果失败,显式强制转换将抛出异常。
1 | var myString = myObject as string; |
它仅检查
1 | var myString = (string)myObject; |
这也寻找从源类型转换为字符串的
阅读第3项:比较Wagner更喜欢
如果无法将对象强制转换为目标类型,则强制转换将抛出异常。