<p>我有一个类似的情况,我需要将附加信息与基本数据类型(如String、int、double,…)相连接<br/>
除了包装它们,我没有找到解决办法。在</p>
<p>您可以尝试通过以下方法优化这些包装类</p>
<ul>
<li>使它们成为const(使用const构造函数</li>
<li>在可能的情况下使字段最终化</li>
<li>其他的也有可能</li>
</ul>
<p><strong>编辑</strong><br/>
-你肯定想去掉所有的switch语句。在</p>
<ol>
<li>0.134285秒:无包装</li>
<li>0.645971秒:使用简化的构造函数、运算符<;=(见下文)<br/>
使用const构造函数并没有造成显著的区别(在转换为JS时可能更重要)</li>
<li>1.449707秒:使用简化的构造函数</li>
<li>3.792590秒:你的密码</li>
</ol>
<pre class="lang-dart prettyprint-override"><code>class $PyNum2 {
final num _value;
const $PyNum2(this._value);
factory $PyNum2.from(value) {
switch ($getType2(value)) {
case 6:
return new $PyNum2(value);
break;
case 7:
try {
return new $PyNum2(num.parse(value));
} catch (ex) {
print("Invalid string literal for num parsing");
exit(1);
}
break;
case 5:
return new $PyNum2(value.value());
break;
default:
throw "Invalid input for num conversion";
}
}
value() => _value;
toString() => _value.toString();
operator +(other) => new $PyNum2(_value + other.value());
operator -(other) => new $PyNum2(_value - other.value());
operator *(other) => new $PyNum2(_value * other.value());
operator ~/(other) => new $PyNum2(_value ~/ other.value());
operator %(other) => new $PyNum2(_value % other.value());
operator ==(other) {
switch ($getType2(other)) {
case 6:
return _value == other;
case 5:
return _value == other.value();
default:
return false;
}
}
operator <(other) {
switch ($getType2(other)) {
case 6:
return _value < other;
case 5:
return _value < other.value();
default:
return true;
}
}
operator >(other) => !(this < other) && (this != other);
operator <=(other) => this.value() <= other.value(); //(this < other) || (this == other);
operator >=(other) => (this > other) || (this == other);
}
</code></pre>
<p>另请参见:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/21744677">Dartlang const constructor - how is it different to "regular" constructor</a></li>
<li><a href="https://groups.google.com/a/dartlang.org/forum/#!topic/misc/qccnux8c6BE" rel="nofollow noreferrer">https://groups.google.com/a/dartlang.org/forum/#!topic/misc/qccnux8c6BE</a></li>
</ul>