了解如何使用C#编程
Console.WriteLine("Hello,World!");
Console 是表示控制台窗口的类型。 WriteLine 是 Console 类型的方法,负责将文本行打印到文本控制台。
其余部分探索了如何使用在 C# 中表示文本的 string 类型。 与 Console 类型一样,string 类型也包含方法。 string 方法处理的是文本。
string aFriend = "Erebus";Console.WriteLine(aFriend);Console.WriteLine("Hello" + aFriend);
还可以用 { 和 } 字符之间放置变量,以告诉C#将该文本替换为此变量的值。这种称为字符串内插。
$ 特殊字符将字符串文本标识为内插字符串。 内插字符串是可能包含内插表达式的字符串文本。
string aFriend = "Bill";Console.WriteLine($"Hello {aFriend}");
与使用字符串复合格式设置功能创建格式化字符串相比,字符串内插提供的语法更具可读性,且更加方便。
如:
string name = "Mark";var date = DateTime.Now;Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");/*输出:Hello, Mark! Today is Wednesday, it's 04:26 now.Hello, Mark! Today is Wednesday, it's 04:26 now.*/
使用Length得出字符串的长度
string a = "Bill";Console.WriteLine($"The name {a} has {a.Length} letters.");/*输出:The name Bill has 4 letters.*/
裁剪字符串中的空格: Trim 方法及相关方法 TrimStart 和 TrimEnd
string a = " Hello,World! ";string b = a.TrimStart();Console.WriteLine($"[{b}]");b = a.TrimEnd();Console.WriteLine($"[{b}]");b = a.Trim();Console.WriteLine($"[{b}]");/*输出:[Hello,World! ][ Hello,World!][Hello,World!]*/
Replace 方法需要使用两个参数。 这两个字符串用括号括住。 第一个字符串是要搜索的文本。 第二个字符串是替换后的文本。
//replace方法、ToUpper和ToLowerstring a = "Hello world";Console.WriteLine(a);a = a.Replace("Hello","Greetings");Console.WriteLine(a);Console.WriteLine(a.ToUpper());Console.WriteLine(a.ToLower());/*输出:Hello worldGreetings worldGREETINGS WORLDgreetings world*/
Contains方法搜索是否包含字符串,返回布尔值string a = "You say goodbye, and I say hell";Console.WriteLine(a.Contains("goodbye"));Console.WriteLine(a.Contains("greeting"));/*输出:TrueFalse*/
//StartsWith和EndsWith,搜索字符串开头或结尾的字符串,针对字符串结尾文本测试时,请注意标点符号。如果字符串以句点结尾,必须检查是否有以句号结尾的字符串。string a = "You say goodbye, and I say hello。";Console.WriteLine(a.StartsWith("you"));Console.WriteLine(a.StartsWith("You"));Console.WriteLine(a.EndsWith("hello。"));/*输出:FalseTrueTrue*/
有关 string 类型的其他阅读材料:
- 字符串中的 C# 编程指南主题。
- 有关使用字符串的操作方法提示。
处理C#中的整数和浮点数
整数
int a =10;int b = 5;int c = a + b;Console.WriteLine(c);/*输出:15*/
整数有一个非常有趣的行为。 整数除法始终生成整数结果,即使预期结果有小数或分数部分也是如此
C# 整数类型不同于数学上的整数的另一点是,int 类型有最小限值和最大限值
int max = int.MaxValue;int min = int.MinValue;Console.WriteLine($"The range of integers is {min} to {max}");/*输出:The range of integers is -2147483648 to 2147483647*/
如果运算生成的值超过这些限值,则会出现下溢或溢出的情况。 答案似乎是从一个限值覆盖到另一个限值的范围。
int max = int.MaxValue;int min = int.MinValue;Console.WriteLine($"The range of integers is {min} to {max}");int what = max + 3;Console.WriteLine($"An example of overflow: {what}");/*输出:The range of integers is -2147483648 to 2147483647An example of overflow : -2147483646*/
双精度浮点型
double数字类型表示双精度浮点数,浮点数可用于表示数量级可能非常大货非常小的非整数,
double a = 5;double b = 4;double c = 2;double d = (a+b)/c;Console.WriteLine(d);//输出:4.5
双精度值的范围远大于整数值
double max = double.MaxValue;double min = double.MinValue;Console.WriteLine($"The range of double is {min} to {max}");/*输出:The range of double is -1.79769313486232E+308 to 1.79769313486232E+308*//*打印出来的这些值用科学计数法表示。E左侧为有效数字,右侧是10的N次幂*/
固定点类型
decimal 类型的范围较小,但精度高于 double。 “固定点”一词意味着,十进制小数点(或二进制小数点)不会移动。范围小于 double 类型。
//计算圆面积double radius = 2.50;double area = Math.PI * radius * radius;Console.WriteLine(area);//输出:19.6349540849362
可以参阅下面的主题,详细了解 C# 中的数字:
- 整型数值类型
- 浮点型数值类型
- 内置数值转换
通过分支和循环语句了解条件逻辑
由于缩进会被忽略,因此通常会对所有if和else子句使用大括号。int a = 5;int b = 6;if (a + b > 10)Console.WriteLine("The answer is greater than 10.");elseConsole.WriteLine("The answer is not greater than 10.");//输出:The answer is greater than 10.//C#忽略缩进或空格
int a = 5;int b = 3;int c = 4;if ((a + b + c > 10) && (a == b)){Console.WriteLine("The answer is greater than 10");Console.WriteLine("And the first number is equal to the second");}else{Console.WriteLine("The answer is not greater than 10");Console.WriteLine("Or the first number is not equal to the second");}
==符号执行相等测试。 使用==将相等测试与赋值测试区分开来,如在a = 5中所见。&&表示“且”。还可以使用||表示“或”。
int counter = 0;while (counter < 10){Console.WriteLine($"Hello World! The counter is {counter}");counter++;}/*输出:Hello World! The counter is 0Hello World! The counter is 1Hello World! The counter is 2Hello World! The counter is 3Hello World! The counter is 4Hello World! The counter is 5Hello World! The counter is 6Hello World! The counter is 7Hello World! The counter is 8Hello World! The counter is 9*/
int counter = 0;do{Console.WriteLine($"Hello World! The counter is {counter}");counter++;} while (counter < 10);
for(int counter = 0; counter < 10; counter++){Console.WriteLine($"Hello World! The counter is {counter}");}
for循环包含三个控制具体工作方式的部分:
1、是for初始值设定项:int counter = 0;
2、是for条件:counter < 10;
3、是for迭代器:最后一部分是 for 迭代器:counter++ 指定在执行 for 语句后面的代码块后,如何修改循环变量
求1到20能被3整除的整数之和
int sum = 0;for(int a = 1;a <= 20;a++){if (a % 3 ==0);{sum = sum +a;}}Console.WriteLine($"The sum is {sum}");//输出:The sum is 210
- If 和 else 语句
- While 语句
- Do 语句
- For 语句
使用泛型列表类型管理数据集合
```csharp var names = new List{“Bill”,”Ana”,”Felipe”}; foreach(var name in names) { Console.WriteLine($”Hello {name.ToUpper()}”); }
//添加删除项 Console.WriteLine(); names.Add(“Maria”); names.Add(“Bill”); names.Add(“Erebus”); names.Remove(“Ana”); foreach (var name in names) { Console.WriteLine($”Hello {name.ToUpper()}!”); }
//用[和]访问项,索引从0开始 Console.WriteLine($”My name is {names[0]}.”); Console.WriteLine($”I’ve added {names[2]} and {names[3]} to the list.”);
//count属性确定列表长度,最大有效索引是用列表项数-1得出。 Console.WriteLine($”The list has {names.Count} people in it”);
//indexof搜索项 var index = names.IndexOf(“Felipe”); if (index != -1) Console.WriteLine($”名字{names[index]}在第{index}位”);
var notfound = names.IndexOf(“Not found”); Console.WriteLine($”未找到索引,返回的索引是{notfound}”);
//sort方法排序项 names.Sort(); foreach (var name in names) { Console.WriteLine($”Hello {name.ToUpper()}!”); }
//创建头两个整数为1的列表。斐波拉契数列,一串以两个1开头的数字。
//斐波那契数列中的每个数字都是前两个数字之和。
var fibonacciNumbers = new List
创建的集合使用 [List<T>](https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1) 类型。 此类型存储一系列元素。 元素类型是在尖括号内指定。<br />[List<T>](https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.generic.list-1) 类型的一个重要方面是,既可以扩大,也可以收缩,方便用户添加或删除元素。使用斐波那契数列,扩展当前生成的程序。 试着编写代码,生成此序列中的前 20 个数字。 (作为提示,第 20 个斐波纳契数是 6765。)```csharpvar fibonacciNumbers = new List<int> {1, 1};while (fibonacciNumbers.Count < 20){var previous = fibonacciNumbers[fibonacciNumbers.Count - 1];var previous2 = fibonacciNumbers[fibonacciNumbers.Count - 2];fibonacciNumbers.Add(previous + previous2);}foreach(var item in fibonacciNumbers)Console.WriteLine(item);
来源:https://docs.microsoft.com/zh-cn/dotnet/csharp/tutorials/intro-to-csharp/local-environment
在计算机上演练教程的第一步是设置开发环境。 .NET 教程 Hello World 10 分钟入门介绍了如何在 Windows、Linux 或 macOS 上设置本地开发环境。
或者,也可以安装 .NET Core SDK 和 Visual Studio Code。
//查看是否安装成功dotnet//查看帮助dotnet -h//新建项目dotnet new console -o 路径dotnet new console -o myApp//跳转到d盘d://跳转到项目路径cd 路径//运行dotnet run//查看文本文件内容----输入help能查看cmd命令type Program.cs//用于发布exe<RuntimeIdentifier>win10-x64</RuntimeIdentifier>//在项目根目录执行命令:运行程序 :dotnet run -p ceshi002.csproj发布exe :dotnet publish ceshi002.csproj
基本的应用程序开发流
dotnet new 命令创建应用程序。 此命令生成应用程序所需的文件和资产。
dotnet build 以生成可执行文件
dotnet run 以运行可执行文件。
探索C#6
导入单个类
//如果在整个代码中反复使用类的静态方法,则每次包含类名都会模糊代码的含义。using static System.Console;
在广泛使用具有许多静态方法的单个类(比如 string 类或 System.Math 类)的大型程序中,static using 语句变得更加有用。
快速且简单的null检查
异常筛选器
使用nameof
nameof 运算符返回任何变量、类型或类型成员的名称。
using System;using System.Collections.Generic;public class Program{public static void Main(){Console.WriteLine(nameof(System.String));int j = 5;Console.WriteLine(nameof(j));List<string> names = new List<string>();Console.WriteLine(nameof(names));}}/*输出Stringjnames*/
输出与变量或类型的名称相匹配。 即使提供了完全限定的类型名称(如 System.String),nameof 运算符也会返回不限定的名称。 如果需要将参数或属性名称转换为字符串,此功能非常有用。 示例包括捕获用于引发 ArgumentNullException 或 ArgumentException 的参数的名称,或者捕获实现 INotifyPropertyChanged 时更改的属性的名称。
新的对象初始化语法
使用字符串内插构造格式化字符串
var name = "<name>";Console.WriteLine($"Hello, {name}. It's a pleasure to meet you!");
包含不同的数据类型
var item = (Name: "eggplant", Price: 1.99m, perPackage: 3);var date = DateTime.Now;Console.WriteLine($"在{date},{item.Name}的价格是{item.Price}/{item.perPackage}斤");
注意,内插字符串中的内插表达式 item.Price 会解析为结果字符串中的“1.99”文本。 这是因为,当表达式结果的类型不是字符串时,会按照以下方式将其解析为字符串:
- 如果内插表达式的计算结果为
null,则会使用一个空字符串(”” 或 String.Empty)。 - 如果内插表达式的计算结果不是
null,通常会调用结果表达式的ToString方法。
在此示例的输出中,日期过于精确(eggplant 的价格不会以秒为单位变化),且价格值没有标明货币单位。
控制内插表达式的格式
Console.WriteLine($"{date:d},价格{item.Name}是{item.Price:C2}/{item.perPackage}斤");
可通过在内插表达式后接冒号(“:”)和格式字符串来指定格式字符串。 “d”是标准日期和时间格式字符串,表示短日期格式。 “C2”是标准数值格式字符串,用数字表示货币值(精确到小数点后两位)。
.NET 库中的许多类型支持一组预定义的格式字符串。 这些格式字符串包括所有数值类型以及日期和时间类型。 有关支持格式字符串的完整类型列表,请参阅 .NET 中的格式化类型文章中的格式字符串和. NET 类库类型。
“t”(显示短时间格式)、“y”(显示年份和月份)和“yyyy”(显示四位数年份)。
“e”(用于指数计数法)和“F3”(使数值在小数点后保持三位数字)。
控制内插表达式的字段宽度和对齐方式
var inventory = new Dictionary<string, int>(){["hammer, ball pein"] = 18,["hammer, cross pein"] = 5,["screwdriver, Phillips #2"] = 14};Console.WriteLine($"Inventory on {DateTime.Now:d}");Console.WriteLine(" ");Console.WriteLine($"|{"Item",-25}|{"Quantity",10}|");foreach (var item in inventory)Console.WriteLine($"|{item.Key,-25}|{item.Value,10}|");
项目名称为左对齐,其数量为右对齐。 通过在内插表达式后面添加一个逗号(“,”)并指定“最小”字段宽度来指定对齐方式。 如果指定的值是正数,则该字段为右对齐。 如果它为负数,则该字段为左对齐。
可合并单个内插表达式中的对齐说明符和格式字符串。
Console.WriteLine($"[{DateTime.Now,-20:d}] Hour [{DateTime.Now,-10:HH}] [{1063.342,15:N2}] feet");
如何在内插字符串中使用转义序列
内插字符串支持所有可在普通字符串文本中使用的转义序列。 有关详细信息,请参阅字符串转义序列。
若要逐字解释转义序列,可使用逐字字符串文本。 内插逐字字符串以 $ 字符开头,后跟 @ 字符。 从 C# 8.0 开始,可以按任意顺序使用 $ 和 @ 标记:$@"..." 和 @$"..." 均为有效的内插逐字字符串。
若要在结果字符串中包含大括号 “{“ 或 “}”,请使用两个大括号 “{{“ 或 “}}”。 有关详细信息,请参阅复合格式设置主题的转义括号部分。
var xs = new int[] { 1, 2, 7, 9 };var ys = new int[] { 7, 9, 12 };Console.WriteLine($"Find the intersection of the {{{string.Join(", ", xs)}}} and {{{string.Join(", ", ys)}}} sets.");var userName = "Jane";var stringWithEscapes = $"C:\\Users\\{userName}\\Documents";var verbatimInterpolated = $@"C:\Users\{userName}\Documents";Console.WriteLine(stringWithEscapes);Console.WriteLine(verbatimInterpolated);
如何在内插表达式中使用三元条件运算符 ?:
因为冒号 (:) 在具有内插表达式的项中具有特殊含义,为了在表达式中使用条件运算符,请将表达式放在括号内。
var rand = new Random();for (int i = 0; i < 7; i++){Console.WriteLine($"{(rand.NextDouble() < 0.5 ? "heads":"tails")}");}
