Dart类型测试在局部变量和类成员变量之间的工作方式不同 [英] Dart type tests work differently between local variable and class member variables

查看:33
本文介绍了Dart类型测试在局部变量和类成员变量之间的工作方式不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用dart时不允许出现隐式的动态变化和强制转换,我注意到以下几点:

I am working with dart without allowing implicit dynamics and casts and I noticed the following:

在使用局部变量时,我可以对该变量进行类型检查,如果测试通过,编译器将假定我可以将该变量用作该类型:

When working with a local variable, I can use a type check on that variable and if the test passes, the compiler will just assume that I can use that variable as that type:

var emp; // set to something
if (emp is Person) {
  // The compiler infers that emp is a person within this scope
  // so it allows me to use Person's member functions and variables
  // without the need for explicit typecast
  // https://dart.dev/guides/language/language-tour#type-test-operators
  emp.firstName = 'Bob';
}

但是,如果变量是对象的成员变量,则此操作不起作用:

However, this does not work if the variable is the member variable of an object:

class SuperPerson {
  Object _emp;

  /* Various things that could be doing things with _emp here */

  void memberFun() {
    if (_emp is Person) {
      _emp.firstName = 'Bob'; // ERROR: The setter firstName is not defined for type Object.
      (_emp as Person).firstName = 'Bob'; // workaround but would like to avoid casts that could fail.
    }
  }
}

为什么会这样,我该如何克服呢?可能是因为其他线程可能在测试和使用之间更改_emp的值吗?

Why is that and how can I overcome it? Could it be because of potentially other threads changing the value of _emp in between the test and the use?

推荐答案

我忘记了我已经回答了这个问题.改为看到那个.

I had forgotten that I had already answered this question. See that one instead.

(由于此答案在编辑时已被接受,因此我无法将其删除.)

(Since this answer had already been accepted at the time of this edit, I cannot delete it.)

这篇关于Dart类型测试在局部变量和类成员变量之间的工作方式不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆