一周学会 C# (前言)
C# 才鸟(QQ:249178521)
大家好! C# 作为微软在 21 世纪推出的新语言,它有着其他语言无法比拟的优势。但如何在短时间内迅速掌握它,却是一个比较难的问题。但如果你看完这个教程后,你一定会理解并掌握 C# 。
这个教程共分六个部分,今天先介绍 C# 中比较基本的概念。
** 1. ** ** 总体框架 ** ** **
**_ Hiker.cs _ ** 类名不一定等于文件名
** using System; // ** ** 每一个程序必须在开头使用这一语句 **
** public sealed class HitchHiker **
** { **
** public static void Main()// ** ** 程序从 ** ** Main ** ** 开始执行 **
** { **
** int result; **
** result = 9 * 6; **
** int thirteen; **
** thirteen = 13; **
** Console.Write(result / thirteen); // ** ** 输出函数 **
** Console.Write(result % thirteen); **
** } **
** } **
** // ** ** 上面各语句的具体用法以后会介绍 ** ** **
** /* ** ** 这个程序用来 ** ** **
** * ** ** 演示 ** ** C# ** ** 的总体框架 **
** */ **
** 注意:上面的程序中,符号 ** ** // ** ** 表示注释,在 ** ** // ** ** 后面的同一行上的内容是注释 ** ** ; **
** /* ** ** 和 ** ** */ ** ** 这间的内容都是注释 ** ** **
你可以在 windows 的命令行提示符下键入: ** csc Hiker.cs **
进行编译产生可执行文件 ** Hiker.exe **
然后 在 windows 的命令行提示符下键入: ** Hiker ** ,你就可以看到在屏幕上显视 42
** ( ** ** 注:你必须装有 ** ** .net framework) **
single-line comment
program
execution
starts
at Main
和 Java 不一样, C# 源 文件名不一定要和 C# 源 文件中包含的类名相同。
C# 对大小写敏感,所以 Main 的首字母为大写的 M( 这一点大家要注意,尤其是熟悉 C 语言的朋友 ) 。
你可以定义一个返回值为 int 的 Main 函数,当返回值为 0 时表示成功:
public static int Main () { ... return 0; }
你也可以定义 Main 函数的返回值为 void :
public static void Main () { ... }
你还可以 定义 Main 函数接收一个 string 数组:
public static void Main (string[] args)
{
foreach (string args in args) {
System.Console.WriteLine(arg);
}
}
程序中的 Main 函数必须为 static 。
** 2. ** ** 标识符 ** ** **
标识符起名的规则:
ü 局部变量、局部常量、非公有实例域、函数参数使用 camelCase 规则;其他类型的 标识符使用 PascalCase 规则。
** privateStyle ** camelCase 规则(第一个单词的首字母小写,其余单词的首字母大写) ** **
** PublicStyle ** PascalCase 规则(所有单词的首字母大写) ** **
ü 尽量不要使用缩写。
** Message ** ** ,而不要使用 ** ** msg ** 。
ü 不要使用匈牙利命名法。
public sealed class GrammarHelper
{ ...
public QualifiedSymbol Optional(AnySymbol symbol)
{ ... }
private AnyMultiplicity optional =
new OptionalMultiplicity();
}
** 3. ** ** 关键字 ** ** **
** C# ** ** 中 ** ** 76 ** ** 个关键字: ** ** **
** abstract as base bool break **
** byte case catch char checked **
** class const continue decimal default **
** delegate do double else enum **
** event explicit extern false finally **
** fixed float for foreach goto **
** if implicit in int interface **
** internal is lock long namespace **
** new null object operator out **
** override params private protected public **
** readonly ref return sbyte sealed **
** short sizeof stackalloc static string **
** struct switch this throw true **
** try typeof uint ulong unchecked **
** unsafe ushort using virtual void **
** while **
** 5 ** ** 个在某些情况下是关键字: ** ** **
**_ get set value add remove _ **
C# 中有 76 个在任何情况下都有固定意思的关键字。另外还有 5 个在特定情况下才有固定意思的标识符。例如, _ value _ 能用来作为变量名,但有一种情况例外,那就是它用作属性 / 索引器的 set 语句的时候是一关键字。
但你可以在关键字前加 @ 来使它可以用作变量名:
int @int = 42;
不过在一般情况下不要使用这种 变量名。
你也可以使用 @ 来产生跨越几行的字符串,这对于产生正则表达式非常有用。例如:
string pattern = @"
( # start the group
abra(cad)? # match abra and optional cad
)+"; # one or more occurrences
如果你要在字符串中包含双引号,那你可以这样:
string quote = @"""quote""";