C# Development Diary (1)-Summary and Practice of Basic Knowledge

1. Download and install (I won’t go into details here if I have it online)

2. Create a project

 

3. Coding

A C# program mainly includes:

  • 1. Namespace declaration
  • 2. A class
  • 3.class attribute
  • 4.main method
  • 5. Statements and expressions

The code system has been written for us.

The using  keyword is used to include the System  namespace in the program  , why include it? Because the Console below is declared in the System;

namespace Test is a namespace declaration;

class Program is a class declaration;

Main method;

Console.WriteLine("Hello World!") is an output statement;

There is no class variable;

using System;

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

 

4. Run 

 

Output rectangle information

 

using System;

namespace Test
{
    public class Rectangle
    {
        private double length;
        private double width;

        public void initData()
        {
            length = 4.5;
            width = 3.5;
        }

        public double getArea()
        {
            return length * width;
        }

        public void display()
        {
            Console.WriteLine("length:"+length);
            Console.WriteLine("width:"+width);
            Console.WriteLine("area:"+getArea());
        }
    }

    class ShowRectangle
    {
        //psvm
        static void Main(string[] args)
        {
            Rectangle r=new Rectangle();
            r.initData();
            r.display();
        }
    }
}

 

type of data

Value type

Reference type: Reference type is divided into object type ( boxing, unboxing ), dynamic type (type checking of object type variable occurs at compile time, and type checking of dynamic type variable occurs at runtime), character String type

Pointer type: The pointer in C# has the same function as the pointer in C or C++

Type conversion

Implicit type conversion: conversion performed in a safe manner without data loss, from a small integer type to a large integer type, and from a derived class to a base class

Explicit type conversion: that is, forced type conversion, which will cause data loss

Basic variable types

Types of For example
Integer type sbyte、byte、short、ushort、int、uint、long、ulong 和 char
Floating point float 和 double
Decimal type decimal
Boolean type true or false value, specified value
Empty type Nullable data type

Constant type

Integer constants, floating-point constants, character constants or string constants, as well as enumeration constants, constants are  defined using the  const keyword, and the constants declared by const cannot be modified

const int c1 = 5;

Operator

Arithmetic Operator

int sum = 0;
int temp = 2;
sum = 10 + 10;//算数加运算

Relational operator

Console.WriteLine(sum==temp);//关系运算

Logical Operators

 Console.WriteLine(true&&false);//逻辑运算

Bit operator

int a = 60; //60 = 0011 1100
int b = 13; //13 = 0000 1101
int c = 0;
c = a & b;  //12 = 0000 1100 与运算
c = a | b;  //61 = 0011 1101 或运算
c = a ^ b;  //49 = 0011 0001 非运算
c = ~a;     //-61 = 1100 0011 取反运算
c = a << 2; //240 = 1111 0000 二进制左移运算符
c = a >> 2; //15 = 0000 1111 二进制右移运算符

Assignment operator

int a2 = 21;
int c2;
c = a;
c += a;
c <<= 2;//等同于 C = C << 2
c &= 2;//等同于 C = C & 2

Other operators

Operator description Instance
sizeof() Returns the size of the data type. sizeof(int), will return 4.
typeof() Returns the type of class. typeof(StreamReader);
& Return the address of the variable. &a; will get the actual address of the variable.
* Pointer to the variable. *a; will point to a variable.
? : Conditional expression If the condition is true? then it is X: otherwise it is Y
is Determine whether the object is of a certain type. If( Ford is Car) // Check whether Ford is an object of Car class.
as Force conversion, even if the conversion fails, no exception will be thrown. Object obj = new StringReader("Hello");
StringReader r = obj as StringReader;

Operator precedence (listed from highest to lowest)

category  Operator  Associativity 
suffix  () [] -> . ++ - -   From left to right 
Unification  + - ! ~ ++ - - (type)* & sizeof  Right to left 
Multiply and divide  * / %  From left to right 
Addition and subtraction  + -  From left to right 
Shift  << >>  From left to right 
relationship  < <= > >=  From left to right 
equal  == !=  From left to right 
Bit and AND  From left to right 
Bitwise XOR  From left to right 
Bit or OR  From left to right 
Logical and AND  &&  From left to right 
Logical OR  ||  From left to right 
condition  ?:  Right to left 
Assignment  = += -= *= /= %=>>= <<= &= ^= |=  Right to left 
comma  From left to right 

Judge sentences

if (true)
{
    Console.WriteLine("true");
}
else
{
    Console.WriteLine("false");
}

Console.WriteLine(c > 0 ? c : 0);

loop statement

//while循环
while(true)
{
    Console.WriteLine("123");
}
//for循环
for (int q=10;q<20;q++) 
{
    Console.WriteLine(q);   
}
//foreach循环
int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
    Console.WriteLine(element);
}
//do-while循环
int w = 10;
do
{
    Console.WriteLine(w);
    w += 1;
} while (w < 20);

Access modifier

  • public: all objects can be accessed;
  • private: The object itself can be accessed inside the object;
  • protected: only objects of this class and its subclasses can be accessed
  • internal: objects in the same assembly can be accessed; any member with internal access modifier can be accessed by any class or method defined in the application defined by the member
  • protected internal: Access is limited to the current assembly or types derived from the contained class.

 Definition method

public int Find(int num1,int num2)
{
    return num1>num2?num1:num2;
}

Call method

static void Main(string[] args)
{
    Program p=new Program();
    p.Find(1, 0);
}

Parameter passing

the way description
Value parameter 这种方式复制参数的实际值给函数的形式参数,实参和形参使用的是两个不同内存中的值。在这种情况下,当形参的值发生改变时,不会影响实参的值,从而保证了实参数据的安全。
引用参数 这种方式复制参数的内存位置的引用给形式参数。这意味着,当形参的值发生改变时,同时也改变实参的值。
输出参数 这种方式可以返回多个值。

 特别说一下输出参数的使用

using System;

namespace Test5
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p=new Program();
            int a, b;
            p.getValues(out a,out b);
            Console.WriteLine(a);
            Console.WriteLine(b);
        }

        public void getValues(out int x,out int y)
        {
            x = 5;
            y = 6;
        }
    }
}

C#中的?

单问号用于对 int,double,bool 等无法直接赋值为 null 的数据类型进行 null 的赋值

using System;

namespace Test6
{
    class Program
    {
        int? i;
        
        static void Main(string[] args)
        {
            Program p=new Program();
            Console.WriteLine(p.get());
        }

        public int? get()
        {
            if (i == null)
            {
                return 0;
            }
            else
            {
                return i;
            }
        }
    }
}

using System;

namespace Test6
{
    class Program
    {
        static void Main(string[] args)
        {
            int? i=null;
            double? num=new double?();
            Console.WriteLine("num:"+num);
            
            Program p=new Program();
            Console.WriteLine("i:"+i);
        }
    }
}

双问号:用于定义可空类型和引用类型的默认值

double? num2 = null;
double num3;
num3 = num2 ?? 5.34; // 如果num2为空则返回5.34
Console.WriteLine(num3);

 数组

using System;

namespace Test7
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] n=new int[10];//申明数组
            // int[] n=new int[]{0,1,2,3,4,5,6,7,8,9}//不需要指定数组大小的方式申明
            for (int i=0;i<10;i++)//数组赋值
            {
                n[i] = i + 100;
            }

            for (int j=0;j<10;j++)
            {
                Console.WriteLine(n[j]);
            }
        }
    }
}
//申明并初始化二维数组
int[,] a = new int[5, 2]
{
    {0, 0}, {1, 2}, {2,4},{3, 6}, {4,8}
};
for (int i=0;i<5;i++) {
    for (int j=0;j<2;j++) {
        Console.WriteLine("a[{0},{1}]={2}",i,j,a[i,j]);
    }
}
//交错数组申明并初始化,交错数组即数组的数组,是一维数组
int[][] a = new int[][]
{
    new int[] {0, 0},
    new int[] {1, 2},
    new int[] {2, 4},
    new int[] {3, 6},
    new int[] {4, 8}
};
for (int i = 0; i < 5; i++)
{
    for (int j = 0; j < 2; j++)
    {
        Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
    }
}
int[] arr = new int[] {1000, 2, 3, 17, 50};
Program p=new Program();
Console.WriteLine(p.getAverage(arr, arr.Length));

public double getAverage(int[] arr,int size)
{
    int sum = 0;
    for (int i = 0; i < size; ++i)
    {
        sum += arr[i];
    }

    return (double)sum / size;
}
//参数数组,适用于不能确定要传递给函数作为参数的参数数目
Program p=new Program();
int sum=p.add(512, 720, 250, 567, 889);
Console.WriteLine(sum);

public int add(params int[] arr)
{
    int sum = 0;
    foreach (int i in arr)
    {
        sum += i;
    }

    return sum;
}
//Array类的使用
int[] list = {34, 72, 13, 44, 25, 30, 10};
// Array.Reverse(list);//数组反转
Array.Sort(list);//从小到大排序,仅支持一维数组
foreach (int i in list)
{
    Console.Write(i + " ");
}

 

字符串

使用以下方法之一来创建 string 对象:

  • 通过给 String 变量指定一个字符串
  • 通过使用 String 类构造函数
  • 通过使用字符串串联运算符( + )
  • 通过检索属性或调用一个返回字符串的方法
  • 通过格式化方法来转换一个值或对象为它的字符串表示形式

 

using System;

namespace Test8
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建字符串对象
            string name = "test";//1

            char[] letters = {'T', 'e', 's', 't', '2'};//2
            string name2=new string(letters);

            string name3 = "test1" + "test2";//3

            string[] sarray = {"Hello", "From", "Tutorials", "Point"};
            string name4 = String.Join("", sarray);//4
            
            
            DateTime time=new DateTime(2020,09,24,16,41,00);
            //string date = String.Format("{0:D} {0:t} ", time);
            //string date = String.Format("{0:yyyy-MM-dd HH:mm:ss}", time);
            string date = time.ToString("yyyy-MM-dd HH:mm:ss");

            Console.WriteLine(date);

            Console.WriteLine(String.Compare(name, name2));//字符串比较
            
            Console.WriteLine(name.Contains("test"));//字符串是否包含
            
            Console.WriteLine(name.Substring(0, 2));//字符串截取
            
            Console.WriteLine(String.Join("|", sarray));//字符串拼接
        }
    }
}

 

using System;

namespace Test9
{
    class Program
    {
        static void Main(string[] args)
        {
            Books books,books2;
            books.title = "1";
            books.author = "user1";
            books.id = 1;
            
            books2.title = "2";
            books2.author = "user2";
            books2.id = 2;
            
            Console.WriteLine(books.title);
            Console.WriteLine(books2.title);
        }
    }
}

struct Books
{
    public string title;
    public string author;
    public int id;
}

 

类和结构有以下几个基本的不同点:

  • 类是引用类型,结构是值类型。
  • 结构不支持继承。
  • 结构不能声明默认的构造函数。
  • 结构体中声明的字段无法赋予初值,类可以。
  • 结构体的构造函数中,必须为结构体所有字段赋值,类的构造函数无此限制。

类与结构的选择

首先明确,类的对象是存储在堆空间中,结构存储在栈中。堆空间大,但访问速度较慢,栈空间小,访问速度相对更快。故而,当我们描述一个轻量级对象的时候,结构可提高效率,成本更低。当然,这也得从需求出发,假如我们在传值的时候希望传递的是对象的引用地址而不是对象的拷贝,就应该使用类了

  •  1、当堆栈的空间很有限,且有大量的逻辑对象时,创建类要比创建结构好一些;
  •  2、对于点、矩形和颜色这样的轻量对象,假如要声明一个含有许多个颜色对象的数组,则CLR需要为每个对象分配内存,在这种情况下,使用结构的成本较低;
  • 3、在表现抽象和多级别的对象层次时,类是最好的选择,因为结构不支持继承。
  • 4、大多数情况下,目标类型只是含有一些数据,或者以数据为主。

枚举

using System;

namespace Test9
{
    class Program
    {

        enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
        
        

        static void Main(string[] args)
        {

            int x = (int)Day.Sun;
            int y = (int) Day.Fri;
            Console.WriteLine(x);
            Console.WriteLine(y);
        }
    }
    
    
}

using System;

namespace HzkTest10
{
    class Program
    {
        static void Main(string[] args)
        {
            Box box1= new Box();
            Box box2 = new Box();
            box1.length = 5.0;
            box1.width = 6.0;
            box1.height = 7.0;
            
            box2.length = 8.0;
            box2.width = 9.0;
            box2.height = 10.0;
            
            Console.WriteLine(box1.length*box1.width*box1.height);
            Console.WriteLine(box2.length*box2.width*box2.height);
            Console.WriteLine(box1.getV());
            Console.WriteLine(box2.getV());
        }
    }

    class Box
    {
        public double length;
        public double width;
        public double height;
        public static int num;//静态成员变量,所有对象公用一个静态成员变量,可以通过直接调用类而不需要创建类的实例来获取

        public Box()//默认构造函数
        {
            Console.WriteLine("对象已创建");
        }

        ~Box()//析构函数,它不返回值,也不带任何参数,用于在结束程序(比如关闭文件、释放内存等)之前释放资源
        {
            Console.WriteLine("对象已删除");
        }

        public Box(double length, double width, double height)//带参数构造函数
        {
            this.length = length;
            this.width = width;
            this.height = height;
        }

        public static int getStatic()//静态成员函数,只能访问静态变量
        {
            return num;
        }

        public double getV()
        {
            return length * width * height;
        }
    }
}

继承

using System;

namespace Test11
{
    class Program
    {
        static void Main(string[] args)
        {
            // Rectangle r=new Rectangle();//不带参数的构造函数
            // r.setWidth(5);
            // r.setHeight(10);
            Rectangle r=new Rectangle(5,10);
            Console.WriteLine(r.getArea());
            r.Display();
        }
    }

    //基类
    class Shape
    {
        protected int width;
        protected int height;

        public Shape(int width, int height)
        {
            this.width = width;
            this.height = height;
        }

        public void Display()
        {
            Console.WriteLine("width:"+width);
            Console.WriteLine("height:"+height);
        }

        public void setWidth(int w)
        {
            width = w;
        }

        public void setHeight(int h)
        {
            height = h;
        }

    }

    //派生类
    class Rectangle : Shape
    {

        private double area;

        public Rectangle(int width, int height) : base(width, height)
        {
        }

        public int getArea()
        {
            return width * height;
        }

        public void Display()
        {
            base.Display();
            Console.WriteLine("Area:"+width*height);
        }
    }
}

多继承

using System;

namespace Test11_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle r=new Rectangle();
            r.setWidth(5);
            r.setHeight(10);
            Console.WriteLine(r.getArea());
            
            int area = r.getArea();
            Console.WriteLine(r.getCost(area));
        }
    }

    class Shape
    {
        protected int width;
        protected int height;
        
        public void setWidth(int w)
        {
            width = w;
        }
        public void setHeight(int h)
        {
            height = h;
        }
    }

    public interface Shape2
    {
        int get();
    }

    public interface PaintCost
    {
        int getCost(int area);
    }

    class Rectangle : Shape, Shape2, PaintCost  //子类只能继承一个父类,但可以继承多个父接口
    {
        public int getCost(int area)
        {
            return area * 70;
        }

        public int get()
        {
            return 0;
        }

        public int getArea()
        {
            return width * height;
        }
    }
}

多态性

静态多态性

函数重载

using System;

namespace Test12
{
    class Program
    {
        static void Main(string[] args)
        {
            Test t=new Test();
            int t1=t.Add(1, 2);
            int t2 = t.Add(1, 2, 3);
            double t3 = t.Add(1, 2.3, 4.625);
        }
    }

    public class Test
    {
        public int Add(int a,int b)
        {
            return a + b;
        }

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

        public double Add(int a,double b,double c)
        {
            return a + b + c;
        }
    }
}

运算符重载

using System;

namespace Test12_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Box box1=new Box();
            Box box2=new Box();
            Box box3=new Box();
            
            box1.setLength(6.0);
            box1.setBreadth(7.0);
            box1.setHeight(5.0);
            
            box2.setLength(12.0);
            box2.setBreadth(13.0);
            box2.setHeight(10.0);

            box3 = box1 + box2;
            Console.WriteLine(box3.getV());
            
        }
    }

    class Box
    {
        private double length;
        private double width;
        private double height;
        
        public void setLength( double len )
        {
            length = len;
        }

        public void setBreadth( double bre )
        {
            width = bre;
        }

        public void setHeight( double hei )
        {
            height = hei;
        }

        public static Box operator+(Box a,Box b)
        {
            Box box=new Box();
            box.length = a.length + b.length;
            box.width = a.width + b.width;
            box.height = a.height + b.height;
            return box;
        }

        public double getV()
        {
            return length * width * height;
        }
    }
}

可重载和不可重载运算符

运算符 描述
+, -, !, ~, ++, -- 这些一元运算符只有一个操作数,且可以被重载。
+, -, *, /, % 这些二元运算符带有两个操作数,且可以被重载。
==, !=, <, >, <=, >= 这些比较运算符可以被重载。
&&, || 这些条件逻辑运算符不能被直接重载。
+=, -=, *=, /=, %= 这些赋值运算符不能被重载。
=, ., ?:, ->, new, is, sizeof, typeof 这些运算符不能被重载

动态多态性

抽象类,用于提供接口的部分类的实现

using System;

namespace Test12_3
{
    class Program
    {
        static void Main(string[] args)
        {
            //Shape s = new Shape();//不能创建抽象类的实例
            Rectangle r=new Rectangle();
            double area=r.area();
        }
    }

    sealed class Shape2//密封类不能被继承
    {
        public int num;
    }

    abstract class Shape
    {
        abstract public int area();
    }

    class Rectangle : Shape
    {
        private int width;
        private int length;
        public override int area()
        {
            return length * width;
        }

        // abstract public int get()//不能在抽象类外部定义抽象方法
        // {
        //     return 0;
        // }
    }
}

当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。以下做一个对比

using System;
using System.Collections.Generic;

namespace HzkTest12_4
{
    class Program
    {
        static void Main(string[] args)
        {
            var shapes = new List<Shape>
            {
                new Rectangle(),
                new Circle()
            };
            foreach (var shape in shapes)
            {
                shape.Draw();
            }
        }
    }

    public class Shape
    {
        public void Draw()
        {
            Console.WriteLine("开始");
        }
    }

    class Circle : Shape
    {
        public  void Draw()
        {
            base.Draw();
            Console.WriteLine("Circle");
        }
    }
    
    class Rectangle : Shape
    {
        public void Draw()
        {
            base.Draw();
            Console.WriteLine("Rectangle");
        }
    }
}

using System;
using System.Collections.Generic;

namespace HzkTest12_4
{
    class Program
    {
        static void Main(string[] args)
        {
            var shapes = new List<Shape>
            {
                new Rectangle(),
                new Circle()
            };
            foreach (var shape in shapes)
            {
                shape.Draw();
            }
        }
    }

    public class Shape
    {
        public virtual void Draw()
        {
            Console.WriteLine("开始");
        }
    }

    class Circle : Shape
    {
        public override void Draw()
        {
            base.Draw();
            Console.WriteLine("Circle");
        }
    }
    
    class Rectangle : Shape
    {
        public override void Draw()
        {
            base.Draw();
            Console.WriteLine("Rectangle");
        }
    }
}

接口

using System;

namespace Test13
{
    class Program:MyInterface
    {
        public void method()
        {
            Console.WriteLine("test");
        }

        static void Main(string[] args)
        {
            Program p=new Program();
            p.method();
        }
    }

    interface MyInterface
    {
        void method();
    }
}
using System;

namespace Test13_2
{
    class Program:MyInterface3
    {
        public void method2()
        {
            Console.WriteLine("2");
        }

        public void method3()
        {
            Console.WriteLine("3");
        }

        static void Main(string[] args)
        {
           Program p=new Program();
           p.method2();
           p.method3();
        }
    }
    
    interface MyInterface2
    {
        void method2();
    }
    
    interface MyInterface3:MyInterface2
    {
        void method3();
    }
}

命名空间

在一个命名空间中声明的类的名称与另一个命名空间中声明的相同的类的名称不冲突

using System;
using test_space;
using test_space2;

namespace Test14
{
    class Program
    {
        static void Main(string[] args)
        {
            test_space.test t1=new test_space.test();
            test_space2.test t2=new test_space2.test();
            t1.func();
            t2.func();
        }
    }
}

namespace test_space
{
    class test
    {
        public void func()
        {
            Console.WriteLine("program");
        }
    }
}

namespace test_space2
{
    class test
    {
        public void func()
        {
            Console.WriteLine("program2");
        }
    }
}

using:指令告诉编译器随后的代码使用了指定命名空间中的名称,例如using System是使用了Console.WriteLine ("...")

嵌套命名空间

using System;

namespace Test14_2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            MyTest.Test.hello();
            MyTest2.Test.hello();
        }
    }

    namespace MyTest
    {
        public class Test
        {
            public static void hello()
            {
                Console.WriteLine("hello!");
            }
        }
    }
}

namespace MyTest2
{
    public class Test
    {
        public static void hello()
        {
            Console.WriteLine("hello2!");
        }
    }
}

预处理指令:

预处理器指令指导编译器在实际编译开始之前对信息进行预处理,所有的预处理器指令都是以 # 开始。且在一行上,只有空白字符可以出现在预处理器指令之前。预处理器指令不是语句,所以它们不以分号(;)结束。一个预处理器指令必须是该行上的唯一指令。

C# 预处理器指令列表

预处理器指令 描述
#define 它用于定义一系列成为符号的字符。
#undef 它用于取消定义符号。
#if 它用于测试符号是否为真。
#else 它用于创建复合条件指令,与 #if 一起使用。
#elif 它用于创建复合条件指令。
#endif 指定一个条件指令的结束。
#line 它可以让您修改编译器的行数以及(可选地)输出错误和警告的文件名。
#error 它允许从代码的指定位置生成一个错误。
#warning 它允许从代码的指定位置生成一级警告。
#region 它可以让您在使用 Visual Studio Code Editor 的大纲特性时,指定一个可展开或折叠的代码块。
#endregion 它标识着 #region 块的结束。
#define PI
#define PI2
using System;
namespace Test15
{
    class Program
    {
        static void Main(string[] args)
        {
            // #if(PI)
            // Console.WriteLine("123");
            // #else
            // Console.WriteLine("234");
            // #endif
            Program p=new Program();
            p.test();
        }

        public void test()
        {
            #if(PI && !PI2)
            Console.WriteLine("123");
            #elif(!PI && PI2)
            Console.WriteLine("234");
            #else
            Console.WriteLine("345");
            #endif
        }
    }
}
public void test2()
{
    #if PI && PI2
    //编译器遇到 #error 指令,就会给用户显示后面的文本,作为一条编译错误消息,然后会立即退出编译
    #error "123"
    #endif
    Console.WriteLine("456");
}

 

public void test3()
{
    #if PI && PI2
    #endif
    //编译器遇到 #warning 指令,会给用户显示 #warning 指令后面的文本,之后编译继续进行
    #warning "234"
    Console.WriteLine("45678");
}

#define PI
#define PI2
using System;
namespace Test15
{
    class Program
    {
        static void Main(string[] args)
        {
            // #if(PI)
            // Console.WriteLine("123");//若PI不存在,则这条语句不编译
            // #else
            // Console.WriteLine("234");//若PI存在,则这条语句不编译
            // #endif
            Program p=new Program();
            p.test5();
        }

        public void test()
        {
            #if(PI && !PI2)
            Console.WriteLine("123");
            #elif(!PI && PI2)
            Console.WriteLine("234");
            #else
            Console.WriteLine("345");
            #endif
        }

        public void test2()
        {
            #if PI && PI2
            //编译器遇到 #error 指令,就会给用户显示后面的文本,作为一条编译错误消息,然后会立即退出编译
            /*#error "123"*/
            #endif
            Console.WriteLine("456");
        }
        
        public void test3()
        {
            #if PI && PI2
            #endif
            //编译器遇到 #warning 指令,会给用户显示 #warning 指令后面的文本,之后编译继续进行
            //#warning "234"
            Console.WriteLine("45678");
        }

        public void test4()
        {
            //使用该指令使代码在屏幕上更好地布局
            #region test4
            // int x;
            // double d;
            #endregion
        }
        
        public void test5()
        {
            //用于改变编译器在警告和错误信息中显示的文件名和行号信息
            #line 164 "123.cs"
            // Core.cs, before the intermediate
            // package mangles it.
            // later on
            #line default
        }
        
         //可以抑制或还原指定的编译警告,可以在类或方法级别执行,对抑制警告的内容和抑制的时间进行更精细的控制
        #pragma warning disable 169
        public class Test
        {
            int never;
        }
        #pragma warning restore 169
    }
}

正则表达式(略)

异常处理

using System;

namespace HzkTest16
{
    class Program
    {
        private int r=0;
        static void Main(string[] args)
        {
            Program p=new Program();
            p.div(25,0);
        }
        
        public void div(int num1,int num2)
        {
            try
            {
                r = num1/num2;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine(r);
            }
        }
    }
    
    
}
using System;

namespace Test16
{
    class Program
    {
        private int r=0;
        static void Main(string[] args)
        {
            Program p=new Program();
            p.div(25,0);
            p.test();
        }
        
        public void div(int num1,int num2)
        {
            try
            {
                r = num1/num2;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine(r);
            }
        }

        public void test()
        {
            MyException my=new MyException();
            try
            {
                my.show();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }

    class MyException
    {
        private int num = 0;
        public void show()
        {
            if(num==0)
            {
                throw (new MyException2("error"));
            }
            else
            {
                Console.WriteLine("success");
            }
        }
    }

    class MyException2 : ApplicationException
    {
        public MyException2(string? message) : base(message)
        {
        }
    }
}

输入与输出

从根本上说,流是通过通信路径传递的字节序列,输入流用于从文件读取数据(读操作),输出流用于向文件写入数据(写操作)

using System;
using System.IO;

namespace Test17
{
    class Program
    {
        static void Main(string[] args)
        {
            FileStream f=new FileStream("test.dat",FileMode.OpenOrCreate,FileAccess.ReadWrite);
            for (int i=1;i<=20;i++) {
                f.WriteByte((byte)i);
            }

            f.Position = 0;//把文件当前位置重置为最开始的位置
            for (int i=0;i<=20;i++) {
                Console.Write(f.ReadByte()+" ");
            }
            f.Close();
        }
    }
}

文本文件的读写

二进制文件的读写

Windows文件系统的操作

 

C#集合

 

C#泛型

 

C#多线程

Guess you like

Origin blog.csdn.net/hzkcsdnmm/article/details/108756656