最常用的语法结构
using System;
using System.Linq;
using System.Linq.Expressions;
// 顶级语句中的变量声明
int number = 42;
string message = "The answer to life, the universe, and everything is";
// 输出变量
Console.WriteLine($"{message} {number}.");
// 函数
// 定义和调用方法
int Add(int a, int b) => a + b;
int add(int a, int b, int c) { return a + b + c; }
Console.WriteLine($"Sum of 1 and 2 is {Add(1, 2)}.");
Console.WriteLine($"Sum of 1 and 2 /3 is {add(1, 2, 3)}.");
// 使用 LINQ
var numbers = new[] { 1, 2, 3, 4, 5 };
var evens = numbers.Where(n => n % 2 == 0).ToArray();
Console.WriteLine("Even numbers: " + string.Join(", ", evens));
// 异常处理
try
{
int zero = 0;
int result = number / zero;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
// loop
for (int i = 0; i < number/10; i++)
{
Console.WriteLine("123");
}
while (number-->0)
{
Console.WriteLine($"number={number}");
}
// switch
int day = 3;
switch(day)
{
case 0:
Console.WriteLine("is 0");
break;
case 1:
Console.WriteLine("is 1");
break;
case 2:
Console.WriteLine("is 2");
break;
case 3:
Console.WriteLine("is 3");
break;
default:
Console.WriteLine("is default");
break;
}
//if compare
if (day == 3)
{
Console.WriteLine("is equal to 3");
}
if (day-1>1)
{
Console.WriteLine("big than 1");
}