日期:2013-02-03  浏览次数:20413 次

一周学会C#(前言续)

C#才鸟(QQ:249178521)

4.标点符号

{ 和 } 组成语句块

分号表示一个语句的结束

using System;

public sealed class Hiker

{

public static void Main()

{

int result;

result = 9 * 6;

int thirteen;

thirteen = 13;

Console.Write(result / thirteen);

Console.Write(result % thirteen);

}

}

一个C#的“类/结构/枚举”的定义不需要一个终止的分号。

public sealed class Hiker

{

...

} // 没有;是正确的

然而你可以使用一个终止的分号,但对程序没有任何影响:

public sealed class Hiker

{

...

}; //有;是可以的但不推荐

在Java中,一个函数的定义中可以有一个结尾分号,但在C#中是不允许的。

public sealed class Hiker

{

public void Hitch() { ... }; //;是不正确的

} // 没有;是正确的

5.声明

声明是在一个块中引入变量

u 每个变量有一个标识符和一个类型

u 每个变量的类型不能被改变

using System;

public sealed class Hiker

{

public static void Main()

{

int result;

result = 9 * 6;

int thirteen;

thirteen = 13;

Console.Write(result / thirteen);

Console.Write(result % thirteen);

}

}

这样声明一个变量是非法的:这个变量可能不会被用到。例如:

if (...)

int x = 42; //编译时出错

else

...

6.表达式

表达式是用来计算的!

w 每个表达式产生一个值

w 每个表达式必须只有单边作用

w 每个变量只有被赋值后才能使用

using System;

public sealed class Hiker

{

public static void Main()

{

int result;

result = 9 * 6;

int thirteen;

thirteen = 13;

Console.Write(result / thirteen);

Console.Write(result % thirteen);

}

}

C#不允许任何一个表达式读取变量的值,除非编译器知道这个变量已经被初始化或已经被赋值。例如,下面的语句会导致编译器错误:

int m;

if (...) {

m = 42;

}

Console.WriteLine(m);// 编译器错误,因为m有可能不会被赋值

7.取值

类型 取值 解释

bool true false 布尔型

float 3.14 实型

double 3.1415 双精度型

char 'X' 字符型

int 9 整型

string "Hello" 字符串

object null 对象