您的位置:首页 > 编程语言 > C#

C# 学习笔记2

2008-09-22 19:54 155 查看
[b]位运算(C#)[/b]

1) &,|,^,~

2) 左移:<< 右移:>>


注意:操作数是整数且无溢出。

using System;

class Test1

{

public static void Main()

{

short a = 10;

ushort b = 10;

int c = 10;

uint d = 10;

Console.WriteLine(~10);

Console.WriteLine("short:{0}",~a);

Console.WriteLine("ushort:{0}",~b);

Console.WriteLine("int:{0}:",~c);

Console.WriteLine("uint:{0}",~d);

//---------------------------------------------

int e = 15;

Console.WriteLine("c={0}, e={1}", c, e);

Console.WriteLine("c&e={0}", c&e);

Console.WriteLine("c|e={0}", c | e);

Console.WriteLine("c^e={0}",c^e);

}

}

/*

D:"C#"Code2>test1

-11

short:-11

ushort:-11

int:-11:

uint:4294967285

c=10, e=15

c&e=10

c|e=15

c^e=5

*/


移位运算举例:

using System;

class Test

{

public static void Main()

{

//右移操作

int x = 16;

Console.WriteLine(x);

int y = x >> 2;

Console.WriteLine(y);

y = y >> 2;

Console.WriteLine(y);

y = y >> 2;

Console.WriteLine(y);

Console.WriteLine("--------------------------------");

//左移操作

int m = 1;

Console.WriteLine(m);

int n = m << 2;

Console.WriteLine(n);

n = n << 2;

Console.WriteLine(n);

n = n << 2;

Console.WriteLine(n);

}

}


/*

D:"C#"Code2>test1

16

4

1

0

--------------------------------

1

4

16

64


*/

//c#中移位操作符只有两种,而JAVA中有三种,多了一个 >>>

其它特殊操作符

1) 三元操作符:? :

2) ++, -- (操作对象: 整型,实型,枚举型)

using System;

class Test

{

public static void Main()

{

int i=3;

int count = (i++)+(i++)+(i++); //key: count=12; i=6;

Console.WriteLine("i={0},count={1}", i, count);

i=3;

count = (++i)+(++i)+(++i); //key: count=15; i=6;

Console.WriteLine("i={0},count={1}", i, count);

}

}


/*

D:"C#"Code2>test1

i=6,count=12

i=6,count=15


*/

3) new操作符

对象/数组/代表创建表达式:

class A{}; A a = new A();

int [] int_arr = new int[10];

delegate double DFunc(int x); DFunc f = new DFunc(5);

4) typeof 操作符

用于获得系统原型对象的类型

using System;

class Test

{

public static void Main()

{

Console.WriteLine(typeof(int));

Console.WriteLine(typeof(System.Int32));

Console.WriteLine(typeof(string));

Console.WriteLine(typeof(double[]));

}

}


/*

D:"C#"Code2>test1

System.Int32

System.Int32

System.String

System.Double[]


*/

5) checked 和 unchecked 操作符

用于整型算术运算时控制当前环境中的溢出检查
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: