C#变量与流程控制
.Net5快发布了,借机整理一下C#的相关基础语法,这篇主要汇总变量与流程控制。包括c#各版本的对应关系,命名空间,变量,表达式,流程控制等基础语法。
文章目录
1. C#版本与.NET版本
C#版本与.NET版本对应关系以及各版本的特性
C#版本 | .NET版本 | 发布日期 | 特性 |
---|---|---|---|
C# 1.0 | .NET Framework 1.0 | 2002-02-13 | 委托、事件 |
C# 1.1 | .NET Framework 1.1 | 2003-04-24 | APM(异步编程模型) |
C# 2.0 | .NET Framework 2.0 | 2005-11-07 | 泛型、匿名方法、迭代器、可空类型 |
C# 3.0 | .NET Framework 3.0 | 2007-11-06 | 隐式类型 |
C# 3.0 | .NET Framework 3.5 | 2007-11-19 | 对象集合初始化、自动实现属性、匿名类型、扩展方法、查询表达式、Lambda表达式、 表达式树、分部类和方法、Linq |
C# 4.0 | .NET Framework 4.0 | 2010-04-12 | 动态绑定、命名和可选参数、泛型的协变和逆变、互操作性 |
C# 5.0 | .NET Framework 4.5 | 2012-08-15 | 异步和等待(async和await)、调用方信息(Caller Information) |
C# 6.0 | .NET Framework 4.6 | 2015-07-20 | C# 6 中的新增功能 |
C# 6.0 | .NET Core 1.0 | 2016-06-27 | |
C# 7.0 | .NET Framework 4.6.2 | 2016-08-02 | C# 7.0 中的新增功能 |
C# 7.1 | .NET Framework 4.7 | 2017-04-05 | C# 7.1 中的新增功能 |
C# 7.1 | . .NET Core 2.0 | 2016-08-14 | .NET Core 2.0 的新增功能 |
C# 7.2 | .NET Framework 4.7.1 | 2017-10-17 | C# 7.2 中的新增功能 |
C# 7.3 | .NET Framework 4.7.2 | 2018-04-30 | C# 7.3 中的新增功能 |
C# 7.3 | .NET Core 2.1 | 2018-05-30 | .NET Core 2.1 的新增功能 |
C# 7.3 | .NET Core 2.2 | 2018-12-04 | .NET Core 2.2 的新增功能 |
C# 8.0 | .NET Framework 4.8 | 2019-04-18 | C# 8.0 中的新增功能 |
C# 8.0 | .NET Core 3.0 | 2019-09-23 | .NET Core 3.0 的新增功能 |
C# 8.0 | .NET Core 3.1 | 2019-12-03 | .NET Core 3.1 的新增功能 |
参考链接:
2. 代码结构与注释
namespace为命名空间,Main为程序的主入口,//为单行注释。/**/为多行注释,///三个斜杆为注释文档,#region与#endregion为折叠代码行宏变量。
2.1 命名空间
// 名称空间别名
using MyAliasNameSpace = csharplearnning.myAliasOne;
namespace csharplearnning
{
namespace myAliasOne
{
public class MyClass
{
public string Name;
}
}
namespace myAliasTwo
{
public class MyClass
{
public string Name;
}
}
namespace System
{
namespace Collections
{
namespace Generic
{
class List<T> { };
}
}
}
}
static void Main(string[] args)
{
// 强制使用using的别名
MyAliasNameSpace::MyClass myclass = new MyAliasNameSpace.MyClass();
myclass.Name = "dahlin";
// 使用顶级根名称空间。
global::System.Collections.Generic.List<int> intList = new List<int>();
ReadKey();
}
2.2 代码结构
/*
多行注释
C#基础语法汇总
卷儿哥
*/
namespace csharplearnning
{
class Program
{
/// <summary>
/// 主入口函数
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
#region 打印测试
// 单行注释
Console.WriteLine("Hello, World!");
Console.ReadKey();
#endregion
}
}
}
3. 变量
3.1 变量类型
- 整数类型
类型 | 别名 | 取值范围 |
---|---|---|
sbyte | System.SByte | -128~127 之间的整数 |
byte | System.Byte | 0~255 之间的整数 |
short | System.Int16 | -32768~32767之间的整数 |
unshort | System.UInt16 | 0~65535之间的整数 |
int | System.Int32 | -2147483648~2147483647之间的整数 |
uint | System.UInt32 | 0~4294967295之间的整数 |
long | System.Int64 | -9223372036854775808~9223372036854775807之间的整数 |
ulong | System.UInt64 | 0~18446744073709551615之间的整数 |
- 浮点类型
类型 | 别名 | 取值范围 |
---|---|---|
float | System.Single | 单精度浮点 32bit |
double | System.Double | 双精度浮点64bit |
decimal | System.Decimal | 高精度 128bit |
- 文本和布尔类型
类型 | 别名 | 取值范围 |
---|---|---|
char | System.Char | 一个Unicode字符,存储0和65535之间的整数 |
string | System.String | 一个字符序列 |
bool | System.Boolean | 布尔值:true或falise |
3.2 类型转换
- 隐式转换
ushort destinationVar;
char sourceVar = 'a';
destinationVar = sourceVar;
WriteLine($"sourceVar :{sourceVar}");
WriteLine($"destinationVar :{destinationVar}");
- 显示转换
byte destinationVar;
short sourceVar = 7;
destinationVar =(byte) sourceVar;
WriteLine($"sourceVar :{sourceVar}");
WriteLine($"destinationVar :{destinationVar}");
string doubleStr = "44.444";
double doubleVar = Convert.ToDouble(doubleStr);
WriteLine($"doubleVar :{doubleVar}");
float floatVar = 14.44F;
string floatString = Convert.ToString(floatVar);
WriteLine($"floatString :{floatString}");
3.3 变量使用
float myFloat = 12.3F;
double myDouble = 12.3;
decimal myDemail = 12.30M;
string myString = "\"my Float\" is";
string myAllString = @"
C:\Temp\DyDir\MyFile.cs,
dahlin
";
Console.WriteLine($"{ myString} { myDouble}");
Console.WriteLine($"myFloat is { myFloat}");
Console.WriteLine($"myDemail is { myDemail}");
Console.WriteLine($"myAllString is { myAllString}");
Console.ReadKey();
4. 表达式
- 数学运算符: +,-,*,/,%
double firstNumber, secondNumber;
string userName;
Console.WriteLine("Enter your name:");
userName = Console.ReadLine();
Console.WriteLine($"Welcome {userName}");
Console.WriteLine("Please give me a number:");
firstNumber = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Now give me another number:");
secondNumber = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($" the sum of {firstNumber} and {secondNumber} is {firstNumber + secondNumber}");
Console.WriteLine($" the result of subtracting {secondNumber} from {firstNumber} is {secondNumber - firstNumber }");
Console.WriteLine($" the product of {firstNumber} and {secondNumber} is {firstNumber * secondNumber}");
Console.WriteLine($" the result of dividing {firstNumber} by {secondNumber} is {firstNumber / secondNumber}");
Console.ReadKey();
- 递增与递减:运算符放在操作数前面的,则操作数是在进行任何计算前受到到运算符的影响;运算符放在操作数的后面,则操作数时在完成表达式的计算后受到运算符的影响。
// 递增与递减运算
int var1;
int var2 = 5;
int var3 = 6;
var1 = var2++ * --var3;
Console.WriteLine($"var1 is {var1}");
5. 流程控制
5.1 布尔运算
- 布尔比较运算符:==, !=, <, >, <=, >=
- 条件布尔运算符:&&, ||
using static System.Console;
using static System.Convert;
namespace csharplearnning
{
class Program
{
/// <summary>
/// 主入口函数
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
WriteLine("Enter an interger:");
int myInt = ToInt32(ReadLine());
bool isLessThan10 = myInt < 10;
bool isBetween0And5 = (0 <= myInt) && (myInt <= 5);
WriteLine($"Integer less than 10? {isLessThan10}");
WriteLine($"Integer between 0 and 5? {isBetween0And5}");
WriteLine($"Exactly one of the above is true? {isLessThan10 ^ isBetween0And5}");
ReadKey();
}
}
}
5.2 分支
5.2.1 三元运算符
WriteLine("Enter an interger:");
int myInt = ToInt32(ReadLine());
string resultString = (myInt < 10) ? "Less than 10" : "Greater than or equal to 10";
WriteLine($"the result is {resultString}");
5.2.2 if 分支
string comparison;
WriteLine("Enter a number:");
double var1 = ToDouble(Console.ReadLine());
WriteLine("Enter another number:");
double var2 = ToDouble(ReadLine());
if(var1 < var2)
{
comparison = "less than";
}
else if (var1 == var2)
{
comparison = " equal to";
}
else
{
comparison = "greater than";
}
WriteLine($"The first number is {comparison} the second number.");
5.2.3 switch分支
其中break可以用return和 goto case 条件 取代。
const string myName = "benjamin";
const string niceName = "andrea";
const string sillyName = "ploppy";
string name;
WriteLine("What is your name?");
name = ReadLine();
switch (name.ToLower())
{
case myName:
WriteLine("You have the same as me !");
break;
case niceName:
WriteLine("My,what a nice name you have!");
break;
case sillyName:
WriteLine("That's a very silly name.");
break;
default:
WriteLine("You write a unknow name!");
break;
}
ReadKey();
5.3 循环
5.3.1 do 循环
double balance, interestRate, targetBalance;
WriteLine("What is your current balance?");
balance = ToDouble(ReadLine());
WriteLine("What is your current annual interest rate (in %)?");
interestRate = 1 + ToDouble(ReadLine()) / 100.0;
WriteLine("What balance would you like to have?");
targetBalance = ToDouble(ReadLine());
int totalYears = 0;
if(balance< targetBalance)
{
do
{
balance *= interestRate;
++totalYears;
} while (balance < targetBalance);
WriteLine($"In {totalYears} year {(totalYears == 1 ? "" : "s")} you 'll have a balance of {balance}.");
}
else
{
WriteLine("the targetBalance is less than balance!");
}
5.3.2 while 循环
double balance, interestRate, targetBalance;
WriteLine("What is your current balance?");
balance = ToDouble(ReadLine());
WriteLine("What is your current annual interest rate (in %)?");
interestRate = 1 + ToDouble(ReadLine()) / 100.0;
WriteLine("What balance would you like to have?");
targetBalance = ToDouble(ReadLine());
int totalYears = 0;
while(balance<targetBalance)
{
balance *= interestRate;
++totalYears;
}
WriteLine($"In {totalYears} year {(totalYears == 1 ? "" : "s")} you 'll have a balance of {balance}.");
5.3.3 for 循环
for (int i = 1; i <= 10; i++)
{
if ((i % 2) == 0)
{
continue;
}
WriteLine($"i = {i}");
}