[英]what is the ^ operator in Dart language?
我注意到 dart 中的運算符 ^ 以前從未見過。 它用於計算哈希碼,詳情見下文。 這是一個代碼片段,檢查我看到的部分哈希碼:
import './color.dart';
import './colors.dart';
class CoreState {
final int counter;
final Color backgroundColor;
const CoreState({
this.counter = 0,
this.backgroundColor = Colors.white,
});
CoreState copyWith({
int? counter,
Color? backgroundColor,
}) =>
CoreState(
counter: counter ?? this.counter,
backgroundColor: backgroundColor ?? this.backgroundColor,
);
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is CoreState &&
runtimeType == other.runtimeType &&
counter == other.counter &&
backgroundColor == other.backgroundColor;
@override
int get hashCode => counter.hashCode ^ backgroundColor.hashCode;
@override
String toString() {
return "counter: $counter\n"
"color:$backgroundColor";
}
}
Dart 語言教程解釋說^
是bitwise XOR
。 此運算符通常用於計算哈希碼。 有關為什么請參閱為什么在 Java hascode 中經常使用 XOR的解釋...
Dart 中的 ^ 運算符代表 XOR。
有關更多詳細信息,請檢查此
在 Dart 中, ^
運算符是用戶可定義的運算符。
它的傳統用途是整數和布爾值的異或 (XOR)。
var x = 170;
x = x ^ 85;
print(x); // 255;
x ^= 85; // Same meaning as `x = x ^ 85;`.
print(x); // 170
和
var oddity = false;
for (var number in someNumbers) {
oddity ^= element.isOdd;
}
// True if an odd number of numbers are odd.
您也可以在自己的類上實現^
運算符。 例如BigInt
和Int32x4
類就是這樣,具有類似的基於 XOR 的含義。
你也可以將它用於不同的事情,比如矩陣求冪:
class Matrix {
// ...
Matrix operator ^(int power) {
RangeError.checkNotNegative(power, "power");
if (this.height != this.width) {
throw UnsupportedError("Can only do exponents of square matrices");
}
var result = Matrix.identity(this.height);
while (power > 0) { // Can be made more efficient!
result *= this;
power -= 1;
}
return result;
}
}
...
var matrix = otherMatrix ^ 2;
運算符的優先級始終相同(僅在&
和|
之間)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.