Dart语言基础之运算符

原文:https://www.dartlang.org/guides/language/language-tour

Dart运算符定义了下表中的运算符。你可以重载它们中的许多运算符,Overridable operators.

Description Operator
unary postfix *expr*++ *expr*-- () [] . ?.
unary prefix -*expr* !*expr* ~*expr* ++*expr* --*expr*
multiplicative * / % ~/
additive + -
shift << >> >>>
bitwise AND &
bitwise XOR ^
bitwise OR |
relational and type test >= > <= < as is is!
equality == !=
logical AND &&
logical OR ||
if null ??
conditional *expr1* ? *expr2* : *expr3*
cascade ..
assignment = *= /= += -= &= ^= etc.

Warning: 运算符优先级是Dart解析器行为的近似值。Dart language specification.

当你使用运算符创建表达式。下面是一些运算符表达式的例子:

a++
a + b
a = b
a == b
c ? a : b
a is T

在运算符表中的运算符,优先级按照行的从上到下递减。

对于有两个操作数的运算符,左操作决定了运算符的运算,例如,一个Vector对象和一个Point对象aVector + aPoint 进行的是Vector的+运算。

算术运算符

Dart 支持寻常的算数运算符。

Operator Meaning
+ Add
Subtract
-expr Unary minus, also known as negation (reverse the sign of the expression)
* Multiply
/ Divide
~/ Divide, returning an integer result
% Get the remainder of an integer division (modulo)

Dart 也支持前缀和后缀增加或减少

Operator Meaning
++var var = var + 1 (expression value is var + 1)
var++ var = var + 1 (expression value is var)
--var var = var – 1 (expression value is var – 1)
var-- var = var – 1 (expression value is var)

关系运算符

Operator Meaning
== Equal; see discussion below
!= Not equal
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

为了测试两个对象是不是一样的东西, == . (在极少情况下要确定两个对象是否same使用 identical() 方法.) ==原理:

  1. If x or y is null, return true if both are null, and false if only one is null.

  2. Return the result of the method invocation x.==(y). (That’s right, operators such as == are methods that are invoked on their first operand. You can even override many operators, including ==, as you’ll see in Overridable operators.)

类型测试运算符

as, is, and is!可以在运行时方便的检查类型.

Operator Meaning
as Typecast (also used to specify library prefixes)
is True if the object has the specified type
is! False if the object has the specified type

obj is T 返回真如果obj实现了接口 T. 例如, obj is Object 永远为真.

as 运算符把对象强制转换为特殊类型. 在多数情况下,亦可以把它用作is后使用这个对象的简写:

if (emp is Person) {
  // Type check
  emp.firstName = 'Bob';
}

你可以用 as 缩短代码:

(emp as Person).firstName = 'Bob';

Note: 上面两种代码并不等效. 若empnull或不是 Person, 第一个例子什么都不做; 第二个会抛异常.

赋值运算符

=给变量赋值,??==仅当变量为null时才赋值

// Assign value to a
a = value;
// Assign value to b if b is null; otherwise, b stays the same
b ??= value;

复合赋值运算符

= –= /= %= >>= ^=
+= *= ~/= <<= &= =

复合赋值运算符原理:

For an operator op: a op= b a = a op b
Example: a += b a = a + b
var a = 2; // Assign using =
a *= 3; // Assign and multiply: a = a * 3
assert(a == 6);

逻辑运算符

Operator Meaning
!*expr* inverts the following expression (changes false to true, and vice versa)
|| logical OR
&& logical AND
if (!done && (col == 0 || col == 3)) {
  // ...Do something...
}

位运算操作符

Operator Meaning
& AND
| OR
^ XOR
~*expr* Unary bitwise complement (0s become 1s; 1s become 0s)
<< Shift left
>> Shift right
final value = 0x22;
final bitmask = 0x0f;

assert((value & bitmask) == 0x02); // AND
assert((value & ~bitmask) == 0x20); // AND NOT
assert((value | bitmask) == 0x2f); // OR
assert((value ^ bitmask) == 0x2d); // XOR
assert((value << 4) == 0x220); // Shift left
assert((value >> 4) == 0x02); // Shift right

条件运算符

Dart有两个运算符,可以让您简明地计算可能需要 if-else语句的表达式:

condition ? expr1 : expr2

If condition is true, evaluates expr1 (and returns its value); otherwise, evaluates and returns the value of expr2.

expr1 ?? expr2

If expr1 is non-null, returns its value; otherwise, evaluates and returns the value of expr2.

When you need to assign a value based on a boolean expression, consider using ?:.

var visibility = isPublic ? 'public' : 'private';

If the boolean expression tests for null, consider using ??.

String playerName(String name) => name ?? 'Guest';

The previous example could have been written at least two other ways, but not as succinctly:

// Slightly longer version uses ?: operator.
String playerName(String name) => name != null ? name : 'Guest';

// Very long version uses if-else statement.
String playerName(String name) {
  if (name != null) {
    return name;
  } else {
    return 'Guest';
  }
}

Cascade notation (..)

Cascades (..) allow you to make a sequence of operations on the same object. In addition to function calls, you can also access fields on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

Consider the following code:

querySelector('#confirm') // Get an object.
  ..text = 'Confirm' // Use its members.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));

The first method call, querySelector(), returns a selector object. The code that follows the cascade notation operates on this selector object, ignoring any subsequent values that might be returned.

The previous example is equivalent to:

var button = querySelector('#confirm');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed!'));

You can also nest your cascades. For example:

final addressBook = (AddressBookBuilder()
      ..name = 'jenny'
      ..email = 'jenny@example.com'
      ..phone = (PhoneNumberBuilder()
            ..number = '415-555-0100'
            ..label = 'home')
          .build())
    .build();

Be careful to construct your cascade on a function that returns an actual object. For example, the following code fails:

var sb = StringBuffer();
sb.write('foo')
  ..write('bar'); // Error: method 'write' isn't defined for 'void'.

The sb.write() call returns void, and you can’t construct a cascade on void.

Note: Strictly speaking, the “double dot” notation for cascades is not an operator. It’s just part of the Dart syntax.

其他运算符

Operator Name Meaning
() Function application Represents a function call
[] List access Refers to the value at the specified index in the list
. Member access Refers to a property of an expression; example: foo.bar selects property bar from expression foo
?. Conditional member access Like ., but the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)

For more information about the ., ?., and .. operators, see Classes.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 210,914评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 89,935评论 2 383
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,531评论 0 345
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,309评论 1 282
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,381评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,730评论 1 289
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,882评论 3 404
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,643评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,095评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,448评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,566评论 1 339
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,253评论 4 328
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,829评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,715评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,945评论 1 264
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,248评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,440评论 2 348

推荐阅读更多精彩内容