Dart类中的静态调用方法(使类可调用) [英] Static call method in Dart Classes (make Classes callable)

查看:3625
本文介绍了Dart类中的静态调用方法(使类可调用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于嵌入式DSL,我希望类的行为像一个函数。这似乎很容易实例( https://www.dartlang.org/articles/emulating-functions/ ),但我不能让类发生。我试着创建一个静态调用一个方法,但这也没有工作。

For an embedded DSL I want classes to behave like a function. It seems easy for instances (https://www.dartlang.org/articles/emulating-functions/) but I couldn't make it happen for classes. I tried creating a static call a method but this didn't work either.

有没有办法或者我必须给类另外一个名字,并使Pconst函数,调用构造函数?

Is there a way or do I have to give the class another name and make Pconst a function, calling the constructor?

class Pconst {
  final value;
  Pconst(this.value);
  static Pconst call(value) => new Pconst(value);

  String toString() => "Pconst($value)";
}

void main() {
  var test = Pconst(10);
  // Breaking on exception: Class '_Type' has no instance method 'call'.

  print("Hello, $test");
}


推荐答案

这个:

class _PConst{
    final value;
    _Pconst(this.value);

    String toString() => "Pconst($value)";
}

PConst(value){
    return new _PConst(value);
}

void main() {
    var test = Pconst(10);

    print("Hello, $test"); //should work ok
}

所以你基本上只是隐藏/包装你的类构造函数bog标准函数。

so your basically just hiding/wrapping your classes constructor behind a bog standard function.

这篇关于Dart类中的静态调用方法(使类可调用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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