简体   繁体   English

Dart 语言中的 ^ 运算符是什么?

[英]what is the ^ operator in Dart language?

I have noticed the operator ^ in dart which never seen before.我注意到 dart 中的运算符 ^ 以前从未见过。 Its being use in calculating the hashcode see below for details.它用于计算哈希码,详情见下文。 Here is a code snippet, check the section hashcode where i saw:这是一个代码片段,检查我看到的部分哈希码:

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";
  }
}

The Dart Language Tour explains that ^ is bitwise XOR . Dart 语言教程解释说^bitwise XOR This operator is typically used for computing hash codes.此运算符通常用于计算哈希码。 For an explanation why see Why is XOR often used in Java hascode...有关为什么请参阅为什么在 Java hascode 中经常使用 XOR的解释...

The ^ operator in Dart stand for XOR. Dart 中的 ^ 运算符代表 XOR。

For more details, check this有关更多详细信息,请检查

In Dart, the ^ operator is a user-definable operator.在 Dart 中, ^运算符是用户可定义的运算符。

The traditional use of it is exclusive-or (XOR) of integers and Booleans.它的传统用途是整数和布尔值的异或 (XOR)。

var x = 170;
x = x ^ 85;
print(x); // 255;
x ^= 85;  // Same meaning as `x = x ^ 85;`.
print(x); // 170

and

var oddity = false;
for (var number in someNumbers) {
  oddity ^= element.isOdd;
}
// True if an odd number of numbers are odd.

You can implement the ^ operator on your own classes too.您也可以在自己的类上实现^运算符。 For example the BigInt and Int32x4 classes do, with similar XOR-based meaning.例如BigIntInt32x4类就是这样,具有类似的基于 XOR 的含义。

You could also use it for different things, say matrix exponentiation:你也可以将它用于不同的事情,比如矩阵求幂:

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;

The precedence of the operator is always the same (just between & and | ).运算符的优先级始终相同(仅在&|之间)。

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

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