|
7.三元操作符
三元操作符(?:)也称条件操作符。对条件表达式"b?x:y",总是先计算条件b,然后进行判断。如果b的值为true,则计算x的值,否则计算y的值。条件运算符为右联运算符,因此该形式的表达式 a ? b : c ? d : e 按如下规则计算:a ? b : (c ? d : e)
8. . 运算符
点运算符用于成员访问。name1 . name2
class
Simple
{
public
int
a;
public
void
b()
{
}
}
Simple s
=
new
Simple();
//
变量 s 有两个成员 a 和 b;若要访问这两个成员,请使用点运算符
s.a
=
6
;
//
assign to field a;
s.b();
//
invoke member function b; |
9.[] 运算符
方括号 ([]) 用于数组、索引器和属性,也可用于指针。
type [] array [ indexexpr ]
其中: type 类型。 array 数组。 indexexpr 索引表达式
10.() 运算符
除了用于指定表达式中运算符的顺序外,圆括号还用于指定转换(类型转换)
( type ) expr 其中:type expr 要转换为的类型名。 expr 一个表达式。转换显式调用从 expr 类型到 type 类型的转换运算符;如果未定义这样的转换运算符,则该转换将失败。
12.自增自减操作符
自增操作符++对变量的值加1,而自减操作符--对变量的值减1。此操作符有前后缀之分。对于前缀操作符,遵循的原则是“先增减,后使用”,而后缀操作符则正好相反,是“先使用,后增减”
using
System;
class
MikeCat
{
public
static
void
Main()
{
double
x,y;
x
=
1.5
;
Console.WriteLine(
++
x);
//
自增后等于2.5
y
=
1.5
; Console.WriteLine(y
++
);
//
先显示1.5后自增
Console.WriteLine(y);
//
自增后等于2.5
}
} |
13.as 运算符
as 运算符用于执行可兼容类型之间的转换。as 运算符用在以下形式的表达式中:expression as type 其中: expression 引用类型的表达式。type 引用类型。
as 运算符类似于类型转换,所不同的是,当转换失败时,as 运算符将产生空,而不是引发异常。在形式上,这种形式的表达式:
expression as type 等效于:expression is type ? (type)expression : (type)null
只是 expression 只被计算一次。
请注意,as 运算符只执行引用转换和装箱转换。as 运算符无法执行其他转换,如用户定义的转换,这类转换应使用 cast 表达式来代替其执行。
using
System;
class
MyClass1
{
}
class
MyClass2
{
}
public
class
IsTest
{
public
static
void
Main()
{
object
[] myObjects
=
new
object
[
6
];
myObjects[
0
]
=
new
MyClass1();
myObjects[
1
]
=
new
MyClass2();
myObjects[
2
]
=
"
hello
"
;
myObjects[
3
]
=
123
;
myObjects[
4
]
=
123.4
;
myObjects[
5
]
=
null
;
for
(
int
i
=
0
; i
<
myObjects.Length;
++
i)
{
string
s
=
myObjects[i]
as
string
;
Console.Write (
"
{0}:
"
, i);
if
(s
!=
null
)
Console.WriteLine (
"
'
"
+
s
+
"
'
"
);
else
Console.WriteLine (
"
not a string
"
);
}
}
}
输出
0
:not a
string
1
:not a
string
2
:
'
hello
'
3
:not a
string
4
:not a
string
5
:not a
string |
|