dart中隐式转换运算符的语法是什么? [英] What is the syntax for implicit cast operator in dart?
问题描述
我想将我的自定义类A的实例转换为int。隐式转换运算符的语法是什么? (我想我记得有这样的功能,但我不能在网上找到它)
I would like to cast instances of my custom class A to int. What is the syntax of the implicit cast operator? (I thought I remembered that there is such a feature but I can't find it on the web)
int a = (new A());
推荐答案
类型注释不允许影响Dart中的行为。如果您没有在已选中模式下运行,请执行以下操作:
Type annotations are not allowed to affect behavior in Dart. If you're not running in checked mode, then this:
int a = new A();
的工作方式与此相同:
var a = new A();
。换句话说,当不处于检查模式时,欢迎您将 A
存储在注释为 int
at run-time. In other words, when not in checked mode, you're welcome to store your A
in a variable annotated as an int
, but no actual conversion takes place.
如果您在检查模式下运行,第一个表单将给您一个运行时异常。
If you are running in checked mode, the first form will give you a runtime exception.
我不确定,但我认为你要求的是一种方法来定义你的类之间的转换 A
和 int
,当转换到 int
时会自动发生。没有这样的事情存在,据我所知。你应该简单地定义一个方法来这样做。例如:
I'm not sure, but I think what you're asking for is a way to define a conversion between your class A
and int
that will happen automatically when "cast" to an int
. No such thing exists, to my knowledge. You should simply define a method to do so. For example:
int a = new A().to_i();
这篇关于dart中隐式转换运算符的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!