C#的不同之路

· 更新于

转自 https://www.runoob.com/csharp/csharp-loops.html

1,循环

`class ForEachTest {     static void Main(string[] args)     {         int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };         foreach (int element in fibarray)         {             System.Console.WriteLine(element);         }         System.Console.WriteLine();     } }`

2,封装

  • public:所有对象都可以访问;
  • private:对象本身在对象内部可以访问;
  • protected:只有该类对象及其子类对象可以访问
  • internal:同一个程序集的对象可以访问(exe或dll算一个程序集);
  • protected internal:访问限于当前程序集或派生自包含类的类型。

3,可空类型

?和??
可空类型(?):表示数据类型在自身的基础上,多加了一个NULL空类型。
合并类型(??):表示当没有数据的时候,用??后面的数据当做默认值。

`//? int i; //默认值0 int? ii; //默认值null    //?? double? num1 = null; double? num2 = 3.14157; double num3; num3 = num1 ?? 5.34;      // num1 如果为空值则返回 5.34 Console.WriteLine("num3 的值: {0}", num3); num3 = num2 ?? 5.34; Console.WriteLine("num3 的值: {0}", num3);  num3 的值: 5.34 num3 的值: 3.14157`

4.1数组

`//数组的声明 double[] balance; int[] a;  //初始化数组 //因为数组是引用类型,所以用new double[] balance = new double[10];  //赋值给数组 balance[0] = 4500.0; //声明时候给数组赋值 double[] balance = { 2340.0, 4523.69, 3421.0}; //创建和初始化时候给数组赋值 int [] marks = new int[5]  { 99,  98, 92, 97, 95}; //可以省略数组的大小 int [] marks = new int[]  { 99,  98, 92, 97, 95}; //赋值一个数组变量到另一个目标数组变量中 //目标和源会指向相同的内存位置 int[] score = marks;`

C# 编译器会根据数组类型隐式初始化每个数组元素为一个默认值 ,比如int默认为0

声明一个数组不会在内存中创建数组 。

4.2多维数组

二维数组:string [,] names;
三维数组:int [ , , ] m;

`int [,] a = new int [3,4] {  {0, 1, 2, 3} ,   /*  初始化索引号为 0 的行 */  {4, 5, 6, 7} ,   /*  初始化索引号为 1 的行 */  {8, 9, 10, 11}   /*  初始化索引号为 2 的行 */ }; int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };  //访问 int val = a[2,3];`

4.3交错数组

就是C的传统数组,使用正常,只是定义时候费劲。

`int[][] a = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}}; //或者用for创建,创建就是new int[][] scores = new int[5][]; for (int i = 0; i < scores.Length; i++)  {    scores[i] = new int[4]; }  //调用 a[i][j]`

4.4函数参数里传数组

`double getAverage(int[] arr, int size)   {arr[i]}    int [] balance = new int[]{1000, 2, 3, 17, 50};  app.getAverage(balance, 5);`

4.5参数数组

params 关键字
C# 提供了 params 关键字,使调用数组为形参的方法时,既可以传递数组实参,也可以传递一组数组元素
就是,既可以传数组名字,也可以直接显式传递数组的数据内容

`public int AddElements(params int[] arr) {int sum = 0;foreach (int i in arr){sum += i;}return sum;}  int sum = app.AddElements(512, 720, 250, 567, 889); Console.WriteLine("总和是: {0}", sum);  总和是: 2938`

5,字符串

6,结构体

类是引用类型,结构是值类型。
结构不支持继承。
结构不能声明默认的构造函数

`struct Books {    private string title;    private string author;    private string subject;    private int book_id;    public void setValues(string t, string a, string s, int id)    {       title = t;author = a;subject = s;book_id =id;    }    public void display()    {Console.WriteLine("Title : {0}", title);Console.WriteLine("Author : {0}", author);Console.WriteLine("Subject : {0}", subject);Console.WriteLine("Book_id :{0}", book_id);    } };   public class testStructure {    public static void Main(string[] args)    {       Books Book1 = new Books(); /* 声明 Book1,类型为 Books */       Books Book2 = new Books(); /* 声明 Book2,类型为 Books */       /* book 1 详述 */       Book1.setValues("C Programming",       "Nuha Ali", "C Programming Tutorial",6495407);       /* book 2 详述 */       Book2.setValues("Telecom Billing",       "Zara Ali", "Telecom Billing Tutorial", 6495700);       /* 打印 Book1 信息 */       Book1.display();       /* 打印 Book2 信息 */       Book2.display();       Console.ReadKey();    } }`

7,枚举

8,类

`using System; namespace BoxApplication {     class Box     {        private double length;   // 长度        private double breadth;  // 宽度        private double height;   // 高度        public void setLength( double len )        {             length = len;        }        public void setBreadth( double bre )        {             breadth = bre;        }        public void setHeight( double hei )        {             height = hei;        }        public double getVolume()        {            return length * breadth * height;        }     }     class Boxtester     {         static void Main(string[] args)         {             Box Box1 = new Box();        // 声明 Box1,类型为 Box             Box Box2 = new Box();                // 声明 Box2,类型为 Box             double volume;                               // 体积             // Box1 详述             Box1.setLength(6.0);             Box1.setBreadth(7.0);             Box1.setHeight(5.0);             // Box2 详述             Box2.setLength(12.0);             Box2.setBreadth(13.0);             Box2.setHeight(10.0);             // Box1 的体积             volume = Box1.getVolume();             Console.WriteLine("Box1 的体积: {0}" ,volume);             // Box2 的体积             volume = Box2.getVolume();             Console.WriteLine("Box2 的体积: {0}", volume);             Console.ReadKey();         }     } }`

8.2类,构造函数

构造函数的名称与类的名称完全相同

`class Line    {       private double length;   // 线条的长度       public Line()       {          Console.WriteLine("对象已创建");       }    } class Line2    {       private double length;   // 线条的长度       public Line2(double len)  // 参数化构造函数       {          Console.WriteLine("对象已创建,length = {0}", len);          length = len;       }    }`

8.3类,析构函数

析构函数的名称是在类的名称前加上一个波浪形(~)作为前缀,它不返回值,也不带任何参数。 析构函数用于在结束程序(比如关闭文件、释放内存等)之前释放资源。析构函数不能继承或重载。

class Line
   {
      private double length;   // 线条的长度
      public Line()  // 构造函数
      {
         Console.WriteLine("对象已创建");
      }
      ~Line() //析构函数
    }

8.4类的静态函数

static 关键字把类成员定义为静态的 , 无论有多少个类的对象被创建,只会有一个该静态成员的副本 。 静态变量可在成员函数或类的定义外部进行初始化。你也可以在类的定义内部初始化静态变量

`using System; namespace StaticVarApplication {     class StaticVar     {        public static int num;         public void count()         {             num++;         }         public int getNum()         {             return num;         }     }     class StaticTester     {         static void Main(string[] args)         {             StaticVar s1 = new StaticVar();             StaticVar s2 = new StaticVar();             s1.count();s1.count();s1.count();s2.count();s2.count();s2.count();                     Console.WriteLine("s1 的变量 num: {0}", s1.getNum());             Console.WriteLine("s2 的变量 num: {0}", s2.getNum());             Console.ReadKey();         }     } }`

9,继承

class Shape
   {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
   }
   // 派生类
   class Rectangle: Shape
   {
      public int getArea()
      {return (width * height);}
   }
   
   Main
   {Rectangle Rect = new Rectangle();
   Rect.setWidth(5);
   Rect.setHeight(7);
   Console.WriteLine("总面积: {0}",  Rect.getArea());
   }

因此父类对象应在子类对象创建之前被创建 。

多重继承指的是一个类别可以同时从多于一个父类继承行为与特征的功能

C# 不支持多重继承。但是,您可以使用接口来实现多重继承。

10,多态性

10.1函数重载

就是参数类型不同,函数名相同。

10.2动态多态性

当一个类被声明为 sealed 时,它不能被继承 。

当有一个定义在类中的函数需要在继承类中实现时,可以使用虚方法。
虚方法是使用关键字 virtual 声明的。
虚方法可以在不同的继承类中有不同的实现。
对虚方法的调用是在运行时发生的。
动态多态性是通过 抽象类 和 虚方法 实现的。