C#教程:C#中的赋值运算符
赋值运算符
赋值运算符有=、+=、−=、*=、/=、%=、&=、|=、^=、<<=、>>=、??等。
赋值操作符的左操作数必须是一个变量、属性访问器或索引访问器的表达式,赋值结果将一个新的数值存放在左操作数所在的内存空间中。
在C# 中,可以对变量进行连续赋值,这时赋值操作符是右关联的,这意味着从右向左操作符被分组,如x=y=z等价于x=(y=z)。
如果操作符两侧的操作数类型不一致,则应先进行类型转换。
本教程来自http://www.isstudy.com
给变量赋值的表达式称为赋值表达式,赋值表达式的值用于给变量赋值。
赋值操作符的运算对象、运算法则及运算结果如表1所示。

表1 赋值操作符的运算规则
在C# 中,所有赋值和自反赋值操作符的优先级都是一样的,比所有其他操作符的优先级都低,是优先级最低的操作符。
示例
赋值和自反赋值操作符的优先级
下面的示例代码演示了赋值和自反赋值操作符的优先级。
using System;
class TestClass
{
static void Main()
{
int i;
double d;
i = 5;
d=i;
d +=i;
Console.WriteLine("i 是 {0},d 是 {1}",i, d);
}
}
输出结果:
i 是 5, d 是 10
d +=i;等于d=d+i; 以下 -= 、 *= 、 /= 、 %= 、&=、|=、^=、 <<= 、>>=与之相同。
“??”是一种比较特殊的赋值运算符,含义是如果“??”运算符的左操作数非空,该运算符将返回左操作数,否则返回右操作数。
示例
??”操作符的使用
下面的示例代码演示了如何对y用“??”运算符进行赋值。
using System;
class TestClass
{
static void Main()
{
int? x = null;//给可以为null的类型赋值
// y = x,如果 x 是 null, 则 y = -1.
int y = x ?? -1;
Console.WriteLine("y是{0}",y);
}
}
输出结果:
y是-1
完整程序代码如下:
★★★★★主程序文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.Text;
namespace _2_05
{
class Program
{
static void Main(string[] args)
{
int i;
double d;
i = 5;
d = i;
d += i;
Console.WriteLine("i 是 {0},d 是 {1}", i, d);
}
}
}
完整程序代码如下:
本教程来自http://www.isstudy.com
★★★★★主程序文件完整程序代码★★★★★
using System;
using System.Collections.Generic;
using System.Text;
namespace _2_06
{
class Program
{
static void Main(string[] args)
{
int? x = null;//给可以为null的类型赋值
// y = x,如果 x 是 null, 则 y = -1.
int y = x ?? -1;
Console.WriteLine("y是{0}",y);
}
}
}