英文:
'as' operator in Dart
问题
I'm new to Dart, and I'm trying to understand the 'as' operator. Initially, I thought it worked like the 'typecast' operator in C, but I'm realizing this may not be the case. Can someone explain the differences and similarities between these two operators?
当我运行我的代码:
double x = 10.25, y = 2.3;
int result = (x / y) as int;
print(result);
我收到一个错误消息,内容如下:
Unhandled exception:
type 'double' is not a subtype of type 'int' in type cast
#0 main (file:///C:/Users/UserName/Documents/VSCode/Dart/Lesson_18/Project_1/bin/main.dart:3:24)
#1 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#2 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)
我熟悉Dart的整数除法运算符,但我对'as'运算符的目的和行为不清楚。
英文:
I'm new to Dart, and I'm trying to understand the 'as' operator. Initially, I thought it worked like the 'typecast' operator in C, but I'm realizing this may not be the case. Can someone explain the differences and similarities between these two operators?
When I run my code:
double x = 10.25, y = 2.3;
int result = (x / y) as int;
print(result);
I receive an error message that reads:
Unhandled exception:
type 'double' is not a subtype of type 'int' in type cast
#0 main (file:///C:/Users/UserName/Documents/VSCode/Dart/Lesson_18/Project_1/bin/main.dart:3:24)
#1 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:297:19)
#2 _RawReceivePort._handleMessage (dart:isolate-patch/isolate_patch.dart:192:26)
I'm familiar with Dart's integer division operator, but I'm unclear on the purpose and behavior of the 'as' operator.
答案1
得分: 3
"as
"是一个强制转换,但也是一个断言。你在说“这个值确实是另一种类型,所以让我们称之为那个类型。” 这与C中的类型转换不同,C中你告诉编译器相信你,并且可能在两个完全不同的类别之间转换类型。
英文:
as
is a cast, but also an assertion. You're saying "this value definitely is actually this other type, so let's call it that." This is different from a typecast in C where you're telling the compiler to trust you, and maybe even converting types between two completely different categories.
See also this discussion and the docs.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论