是否可以让操作员在操作中使用先前值

时间:2015-04-22 11:54:47

标签: dart operators

我知道单个操作员不应该,并且不能在两个"方向"中使用。但我想知道每个方向是否有一个操作员,我想念哪一个。 我的问题用一个例子解释得更简单,所以这里是:

void main(){
  int i = 1;
  Test y = new Test(2);
  print(y+i); // Working, print 3
  print(i+y); // Not working crash, I would like this to work
}

class Test {
  dynamic _data;
  Test(value) : this._data = value;
  operator+(other) => _data + value;
  toString() => _data.toString();
}

因为我无法在类int中添加运算符,是否有其他运算符要在类Test中实现以支持此操作。

1 个答案:

答案 0 :(得分:1)

简单的答案是“不”。您只能将numintdouble)添加到int。

如果结果应为int,则可以添加int getter

class Test {
  dynamic _data;
  Test(value) : this._data = value;
  operator+(other) => _data + value;
  toString() => _data.toString();
  int asInt => _data;
}

print(i+y.asInt);

在这种情况下有点危险,因为_data是动态的。

您可以使用泛型

class Test<T> {
  T _data;
  Test(this._data);
  operator+(other) => _data + value; // 
  toString() => _data.toString();
  T asBaseType => _data;
}