简体   繁体   English

如何在构造函数上使用命名参数的Dart类中添加吸气剂?

[英]How can I add a getter to a Dart class with a named parameter on its constructor?

Suppose I have the following Dart class, with a named parameter in its constructor: 假设我有以下Dart类,其构造函数中有一个命名参数:

class TestClass {
  final int someValue;
  TestClass({this.someValue});
}

void someMethod() {
  TestClass testClass = new TestClass(someValue: 10);
  print(testClass.someValue);
}

How can I add a getter for the field? 如何为该字段添加吸气剂? I was trying something along the lines of: 我正在尝试以下方法:

class TestClass {
  final int _someValue;
  TestClass({this.someValue});
  int get someValue => _someValue+2;
}

Named parameters can't be private, but you can get the results you want using a named parameter, a private member, and an initializer. 命名参数不能是私有的,但是您可以使用命名参数,私有成员和初始化程序来获得所需的结果。 You could do the same thing in the constructor body without the initializer, but then _someValue couldn't be final. 您可以在没有初始化程序的情况下在构造函数主体中执行相同的操作,但是_someValue可能不是最终的。

class TestClass {
  final int _someValue;

  TestClass({int someValue}) : _someValue = someValue;

  int get someValue => _someValue;
}

However, there is very little value to doing this in Dart. 但是,在Dart中执行此操作几乎没有价值。 A getter without a corresponding setter is semantically equivalent to a final field. 没有对应的setter的getter在语义上等同于final字段。

TestClass({this.someValue});

There's no member variable by that name. 该名称没有成员变量。 Did you mean _someValue ? 您是说_someValue吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM