熟悉又陌生的第一段代码

码巢新建项目时选 Hello World 模板,你会看到这样一段代码:

using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, CodeNest!");
        }
    }
}

自上而下读一遍:

  • using System; 表示要用 System 命名空间里的东西,Console 就在里面。写在文件最上方。
  • namespace HelloWorld { } 是命名空间,用来给代码分组、避免重名。初学阶段把它当成一个大盒子即可。
  • class Program { } 是类。C# 的代码必须写在类里面,不能像脚本那样随处写。
  • static void Main(string[] args) 是程序入口。运行项目时,就是从 Main 的第一行开始执行的。
  • Console.WriteLine(...) 输出一行文字到下方控制台。

写代码时注意:C# 区分大小写,console.WriteLine 和 main 都会报错;每条语句以分号 ; 结尾;大括号成对出现。

变量与常用类型

变量是给数据起的名字。声明时先写类型,再写名字:

int age = 18;                 // 整数
double price = 9.9;           // 小数
bool isReady = true;          // 布尔值:true / false
char grade = 'A';             // 单个字符,用单引号
string name = "码巢";          // 文本,用双引号

几个常用类型:

类型 含义 示例
int 32 位整数 int count = 42;
long 更大的整数 long big = 9000000000L;
double 小数 double pi = 3.14;
decimal 金额等需要精确的小数 decimal money = 19.9m;
bool 真 / 假 bool ok = false;
char 单个字符 char c = 'A';
string 一串文本 string s = "你好";

类型也可以交给编译器推断,用 var:

var city = "成都";     // 等价于 string city = "成都";
var total = 3 + 4;     // 等价于 int total = 7;

var 只是少写一个类型名,变量本身的类型仍然确定,不能一会儿是数字一会儿是文字。

需要不变的量用 const:

const double TaxRate = 0.06;

字符串与插值

把变量拼进文字,推荐用 $ 插值,比用 + 拼接更清楚:

string name = "小明";
int score = 95;
Console.WriteLine($"你好,{name}!你的分数是 {score} 分。");

输出:

你好,小明!你的分数是 95 分。

大括号里除了变量,也可以写表达式:

int a = 3, b = 4;
Console.WriteLine($"斜边的平方是 {a * a + b * b}");

字符串常用写法还有:

string multi = "第一行\n第二行";        // \n 换行
string quote = "他说:\"你好\"";         // \" 表示一个双引号
string tab = "列一\t列二";               // \t 制表符

运算符

int a = 7, b = 2;

Console.WriteLine(a + b);   // 9   加
Console.WriteLine(a - b);   // 5   减
Console.WriteLine(a * b);   // 14  乘
Console.WriteLine(a / b);   // 3   整数相除,小数部分被丢掉
Console.WriteLine(a % b);   // 1   取余数

想让 7 / 2 得到 3.5,至少让一边是小数:

Console.WriteLine(7 / 2.0);      // 3.5
Console.WriteLine((double)7 / 2); // 强制转换后再除,同样得 3.5

比较运算的结果是 bool:

Console.WriteLine(a > b);    // True
Console.WriteLine(a == b);   // False  判断相等用两个等号
Console.WriteLine(a != b);   // True

逻辑运算用于组合条件:

bool canEnter = age >= 18 && hasTicket;   // 两个都成立
bool discounted = isStudent || isSenior;  // 任一成立
bool notReady = !isReady;                 // 取反

赋值运算有简写:

int n = 10;
n += 5;   // 等价于 n = n + 5;   现在 n 是 15
n -= 3;   // 12
n *= 2;   // 24
n++;      // 自增 1,现在是 25

条件判断

int score = 86;

if (score >= 90)
{
    Console.WriteLine("优秀");
}
else if (score >= 60)
{
    Console.WriteLine("及格");
}
else
{
    Console.WriteLine("需要努力");
}

如果只是给一个变量赋值,用三元运算符更紧凑:

string level = score >= 60 ? "及格" : "不及格";

分支较多且都在判断同一个变量时,用 switch:

int day = 3;
switch (day)
{
    case 1:
        Console.WriteLine("周一");
        break;
    case 2:
        Console.WriteLine("周二");
        break;
    case 6:
    case 7:
        Console.WriteLine("周末");
        break;
    default:
        Console.WriteLine("其他日子");
        break;
}

break 不能省略,否则编译器会直接报错;default 是都没匹配上时执行的兜底分支。

循环

for 适合「知道要循环多少次」:

for (int i = 1; i <= 5; i++)
{
    Console.WriteLine($"第 {i} 次");
}

while 适合「满足条件就一直循环」:

int count = 0;
while (count < 3)
{
    Console.WriteLine($"count = {count}");
    count++;
}

foreach 适合遍历一组数据:

string[] fruits = { "苹果", "香蕉", "橘子" };
foreach (string fruit in fruits)
{
    Console.WriteLine(fruit);
}

循环里两个控制语句:

for (int i = 1; i <= 10; i++)
{
    if (i == 3)
    {
        continue;   // 跳过本次,进入下一次循环
    }
    if (i > 6)
    {
        break;      // 直接结束整个循环
    }
    Console.WriteLine(i);
}

方法:把重复代码装进盒子

static int Add(int a, int b)
{
    return a + b;
}

static void SayHello(string name)
{
    Console.WriteLine($"你好,{name}!");
}

static void Main(string[] args)
{
    SayHello("小明");
    int sum = Add(3, 5);
    Console.WriteLine($"3 + 5 = {sum}");
}

要点:

  • static 表示这个方法属于类本身,可以直接调用,不必先创建对象。
  • void 表示不返回结果;写了 int 就必须 return 一个整数。
  • 括号里是参数,调用时按顺序传入。

方法可以给参数设默认值,也可以按名字传参:

static void Greet(string name, string greeting = "你好")
{
    Console.WriteLine($"{greeting},{name}!");
}

static void Main(string[] args)
{
    Greet("小红");                    // 你好,小红!
    Greet("Tom", "Hello");            // Hello,Tom!
    Greet(greeting: "早上好", name: "小刚"); // 早上好,小刚!
}

注释:写给人和未来的自己

// 单行注释

/*
   多行注释,
   可以写好几行
*/

/// <summary>
/// 这是 XML 文档注释,写在方法上方时,编辑器会提示参数含义。
/// </summary>
static int Square(int x)
{
    return x * x;
}

写完就运行

在码巢里点顶部栏的 运行,编译结果和控制台输出会显示在底部。编译报错时会直接标出行号,例如 CS1002 第 6 行: 应输入 ;,点一下就能跳到那行。

初学阶段最常见的四类报错:

报错编号 常见原因
CS1002 忘了写分号
CS0103 名字拼错,或变量在使用前没声明
CS0029 类型对不上,例如把文字赋给了 int
CS5001 没有 Main 方法,或 Main 写在了类外面

下一步