现在的位置: 首页 > 综合 > 正文

chap02 C#语言基础知识

2013年07月21日 ⁄ 综合 ⁄ 共 1824字 ⁄ 字号 评论关闭

环境

visual studio 2010 

.net framework 4.0

1.  编译 & 反汇编

1.1 编译 csc.exe /out:c:\test.exe c:\test.cs

1.2 反汇编 用IL反汇编工具,打开 test.exe 然后存储。

2. 数组

int[,] points = new int[3,2]{{1, 2}, {2, 3}, {3, 4}};

如果不赋值默认值应该是0(书上说是null)。

3. 类型转换

int a = int.Parse("3");
int b = (int)3.14;
int c = System.Convert.ToInt32(3.14);
float d = System.Convert.ToSingle("3.14");
string e = 3.14.ToString();
Console.WriteLine("a = {0}, b = {1}, c = {2}, d = {3}, e = {4}", a,b,c,d,e);

output:a = 3, b = 3, c = 3, d = 3.14, e = 3.14

4.  注释方式

4.1 //, ///

4.2 /* */

4.3

#region introdoction  

...

#endregion

5. 关键字解析(部分)

5.1 foreach语句

foreach语句用于遍历集合中所有的元素,但这需要特定的接口支持 

int[] array = new int[]{1,2,3};

foreach(int item in array)

  Console.WriteLine(item);

5.2 lock语句

lock 关键字将语句块标记为临界区,方法是获取给定对象的互斥锁,执行语句,然后释放该锁。 

5.3 checked & unchecked

关键字用于取消整型算术运算和转换的溢出检查。
const int ConstantMax = int.MaxValue;

int1 = unchecked(ConstantMax + 10); // 不会报错

5.4 using

using ( StreamWriter sw = File.CreateText('test.txt'))

{

  sw.WriteLine("Line 1");

  sw.WriteLine("Line 2");

}

5.5 yield

static IEnumerable Range(int from, int to)

{

  for(int i = from; i < to; i++)

    yield return i;

}

static void Main()

{

  foreach(int item in Range(-5, 5)

    Console.Write(item + ",");

}

5.6 unsafe和fixed

static int x = 2; 

unsafe static void F(int *p)

{    *p = 1;    }

static void Main()

{

unsafe

{

fixed (int *p = &x) F(p);

Console.WriteLine(x); 

}

指针指向的内存一定要固定。凡是C#里的引用类型(一切类型的数组都是引用类型)都是分配在托管堆上的,都不固定。有两种方法强制固定,一种是用stackalloc分配在栈上,另一种是用fixed分配在堆上。 

5.7 typeof

用于获取类型的 System.Type 对象。 typeof 表达式采用以下形式:

System.Type type = typeof(int);

若要获取表达式的运行时类型,可以使用 .NET Framework 方法 GetType,如以下示例中所示:

 int i = 0;

System.Type type = i.GetType();

5.8 Lambda 表达式

delegate int del(int i, int j);

static void Main(string[] args)
{
     del myDelegate = (x, y) => x * y;
     int j = myDelegate(5, 20);
     Console.WriteLine(j);

}

5.9 as 和 is

is T

如果 x 为 T,则返回 True;否则返回 False。

as T

返回类型为 T 的 x,如果 x 不是 T,则返回 null

5.10 ?? 

null 合并

?? y

如果 x 为 Null 则计算结果为 y,否则计算结果为 x

5.11 new

作为操作符的new用于在堆上创建对象和调用构造函数,值得注意的是值类型对象(例如结构)是在栈上创建的,而引用类型对象(例如类)是在堆上创建的。

 

 

6 异常检查

throw, try-catch, try-finally, try-catch-finally


抱歉!评论已关闭.