‘as’操作符在Dart中使用。

huangapple go评论56阅读模式
英文:

'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 &#39;double&#39; is not a subtype of type &#39;int&#39; in type cast
#0      main (file:///C:/Users/UserName/Documents/VSCode/Dart/Lesson_18/Project_1/bin/main.dart:3:24)
#1      _delayEntrypointInvocation.&lt;anonymous closure&gt; (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.

huangapple
  • 本文由 发表于 2023年5月6日 16:45:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76187958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定