C# 第一篇 踏上征程
一、编写第一个C#程序
实现屏幕输出Hello World!! ,新建控制台应用程序-编写输出语句,以下为c#语句基本结构,带基本注释:
//引用命名空间 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //命名空间 namespace ConsoleApp1 { //Class 类 class Program { //方法 static void Main(string[] args) { //输出文字Hello World!! Console.WriteLine("Hello World!!"); //读取一行输入内容 Console.ReadLine(); } } }
二、C#程序结构
一个C#程序总体分为命名空间、类、关键字、标识符、Main方法、C#语句、注释等;
1、使用using引入命名空间
//引用命名空间 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
2、使用namespace声明命名空间
//命名空间 namespace 命名空间名 { ... }
可使用using引入命名空间,或者使用命名空间名.类名引用命名空间内容;
demo.operation oper = new demo.operation();//创建demo命名空间中operation类的对象
3、声明类
类是一种数据结构,可以封装数据成员、方法成员和其他类。
class 类名 { ... }
PS:关键字与标识符
3.1关键字
关键字是C#中被赋予特定意义的一些单词,例如:using、class、namespace、static、void、public、private、int、this、string、if、while、for等;
3.2标识符
由任意字母、下划线、数字组成,首字母不能为数字,也不能为关键字,例如:_username、username、name1等;
4、Main方法与创建方法
Main方法是一个类体中的主入口方法,static和void分别是Main方法的静态修饰符和返回值修饰符;
class Program { //方法 static void Main(string[] args) { ... } }
5、C#语句
C#语句是构造C#程序的基本单位,C#语句可以声明变量和常量、调用方法、创建对象或执行任何逻辑操作,必须以“;”终止;
Console类下包含4种输入、输出相关的4个方法:
//输出文字Hello World!! Console.WriteLine("Hello World!!"); //输出一个字符 Console.Write("H"); //读取输入的一行信息 Console.ReadLine(); //读取输入的一个字符 Console.Read();
6、C#的注释
C#中的注释分为行注释和块注释,分别以“//”开头的一行与以"/*"开始,“*/”结束;
7、程序编写规范
7.1 统一代码的缩进格式;
7.2 分行编写代码;
7.3 尽量不使用goto语句;
7.4 避免编写超过5个参数的方法,如多个建议使用结构;
7.5 避免编写代码量过大的try-catch语句块;
7.6 避免在同一个文件中编写多个类;
7.7 局部变量在使用它的地方声明;
7.8 良好的注释有利于代码的管理;
7.9 尽量使用接口,然后使用类实现接口,以提高程序的灵活性;
7.10 生成和构建一个长字符串尽量使用 stringBuider类型,而不是string;
7.11 switch语句,一定要有default语句来处理意外情况;
7.12 命名规范统一,尽量使用Pascal 命名法来命名方法和类型(该方法第一个字母大写其他小写,连接单词易一致);