在函数中使用静态变量()

时间:2014-03-30 17:16:21

标签: dart

我知道我们是否可以在函数中声明静态var,就像在JavaScript中一样。

当我回调我的功能时,我的变量会保持最后的效果。

或者我可以只使用全局变量(它不性感......)?

4 个答案:

答案 0 :(得分:6)

您无法在函数中使用静态。

Dart中的全局变量没有代码味道,因为它们只是库全局 JavaScript中的全局变量很难看,因为它们可能与来自第三方库的全局变量冲突 这在Dart中不会发生。

因为你可以在Dart中创建一个尽可能小的库(例如只有一个变量),并且当你导入它时你有类似于库的命名空间的东西,如

import 'my_globals.dart' as gl;

然后像

一样使用它
print(gl.myGlobalValue);

这没有代码味道。

您还可以创建一个类来模拟像

这样的命名空间
class MyGlobals {
  static myVal = 12345;
}

但是Dart中首选库全局变量,而不是仅包含静态变量或函数的类。

答案 1 :(得分:4)

您可以使用函数对象来维护状态:

library test;

class Test implements Function {
  var status = 0;
  static var static_status = 10;

  call() {
    print('Status: $status');
    print('Static status: $static_status');
    status++;
    static_status++;
  }
}

void main() {
  var fun = new Test();

  fun();
  fun();
  fun();

  var fun2 = new Test();

  fun2();
  fun2();
  fun2();
}

输出:

Status: 0
Static status: 10
Status: 1
Static status: 11
Status: 2
Static status: 12
Status: 0
Static status: 13
Status: 1
Static status: 14
Status: 2
Static status: 15

答案 2 :(得分:1)

您只能使用全局变量。

你也可以通过私人变量用#34; mangling"来解决这个问题。名。

void main() {
  myFunction();
  myFunction();
  myFunction();
}

int _myFunction$count = 0;

void myFunction() {
  print(_myFunction$count++);
}

这没有多大帮助,但您可以考虑名称为" _myFunction $ count"的变量。是一个局部静态变量" count"在功能" myFunction"。

与此伪代码相同。

void myFunction() {
  static int count = 0;
  print(count++);
}

答案 3 :(得分:1)

您可以使用Closures,在此示例中,我创建了一个计数器,如下所示:

void mian(){
 var my_counter = counter(5);
 for (var i = 0; i < 10; i++) {
   print(my_counter());
 }
}

Function counter(int n) {
  var number = 0;
  var func = () {
    if (number < n) {
      number++;
      return number;
    } else {
      number = 1;
      return number;
    }
  };
  return func;
}

或发电机:

Iterable<int> count(int n) sync* {
  var number = 0;
  while (number < n) {
    yield number++;
  }
}
相关问题