初学C#-----笔记二

来源:互联网 发布:mac跳过创建电脑账户 编辑:程序博客网 时间:2024/06/06 07:18

续接C#的笔记一,继续我的菜鸟笔记。

一、可空类型Nullable
这是C++中所不具备的。可空类型可以表示其基础值类型正常范围内的值,再加上一个null值。例如:
Nullable< Int32 >,读作”可空的 Int32”,可以被赋值为 -2,147,483,648 到 2,147,483,647 之间的任意值,也可以被赋值为 null 值。类似的,Nullable< bool > 变量可以被赋值为 true 或 false 或 null。

在处理数据库和其他包含可能未赋值的元素的数据类型时,将 null 赋值给数值类型或布尔型的功能特别有用。例如:
数据库中的布尔型字段可以存储值 true 或 false,或者,该字段也可以未定义。

以下是可空数据类型的用法:

using System;namespace CalculatorApplication{    class NullableAtShow    {        static void Main(string[] args)        {            int? num1 = null;            int? num2 = 45;            double? num3 = new double?();            double? num4 = 3.14157;            bool? boolval = new bool?();            //显示值            Console.WriteLine("显示可空类型的值:{0},{1},{2},{3}",num1,num2,num3,num4);            Console.WriteLine("一个可空的布尔值:{0}",boolval);            Console.ReadLine();        }    }}

运行结果如下:

显示可空类型的值:,45,,3.14157一个可空的布尔值:

二、Null合并运算符(??)
Null合并运算符用于定义可空类型和引用类型的默认值。Null合并运算符为类型转换定义了一个预设值,以防可空类型的值为Null。Null合并运算符把操作类型隐式转换为另一个可空(或不可空)的值类型的操作数的类型。
如果第一个操作数的值为null,则运算符返回第二个操作数的值,否则返回第一个操作数的值。例如:

using System;namespace CalculatorApplication{    class NullableAtShow    {        static void Main(string[] args)        {            double? num1 = null;            double? num2 = 3.14157;            double num3;            num3 = num1 ?? 5.34;            Console.WriteLine("num3的值:{0}",num3);            num3 = num2 ?? 5.34;            Console.WriteLine("num3的值:{0}",num3);            Console.ReadLine();        }    }}

运行结果如下:

num3的值:5.34num3的值:3.14157

三、数组
C#中的数组和C++中的没有太多差别,这里有一个foreach语句,可以遍历数组。用法如下例:

using System;namespace ArrayApplication{    class MyArray    {        static void Main(string[] args)        {            int [] n = new int[10]; /*n是一个带有10个整数的数组*/            /*初始化数组n中的元素*/            for(int i = 0;i < 10;i++)            {                n[i] = i + 100;            }            /*输出每个数组元素的值*/            foreach(int j in n)            {                int i = j - 100;                Console.WriteLine("Element[{0}] = {1}",i,j);            }            Console.ReadKey();        }    }}

输出结果如下:

Element[0] = 100Element[1] = 101Element[2] = 102Element[3] = 103Element[4] = 104Element[5] = 105Element[6] = 106Element[7] = 107Element[8] = 108Element[9] = 109

C#里的数组还有几个细节需要注意一下,有多维数组、交错数组、传递数组给函数、参数数组、Array类。其中数组的表示方法和C++略有区别,比如多维数组,举例如下:

using System;namespace ArrayApplication{    class MyArray    {        static void Main(string[] args)        {            /*一个带有5行2列的数组*/            int[,] a = new int[5,2]{{0,0},{1,2},{2,4},{3,6},{4,8}};            int i,j;            /*输出数组中每个元素的值*/            for(i = 0;i < 5;i++)            {                for(j = 0;j < 2;j++)                {                    Console.WriteLine("a[{0},{1}] = {2}",i,j,a[i,j]);                }            }            Console.ReadKey();        }    }}

输出结果如下:

a[0,0] = 0a[0,1] = 0a[1,0] = 1a[1,1] = 2a[2,0] = 2a[2,1] = 4a[3,0] = 3a[3,1] = 6a[4,0] = 4a[4,1] = 8

交错数组,就是数组中的数组,举例如下:

using System;namespace ArrayApplication{    class MyArray    {        static void Main(string[] args)        {            /*一个由5个整型数组组成的交错数组*/            int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},new int[]{2,4},new int[]{3,6},new int[]{4,8}};            int i,j;            for(i = 0; i < 5; i++)            {                for(j = 0; j < 2;j++)                {                    Console.WriteLine("a[{0}][{1}] = {2}",i,j,a[i][j]);                }            }            Console.ReadKey();        }    }}

输出结果如下:

a[0][0] = 0a[0][1] = 0a[1][0] = 1a[1][1] = 2a[2][0] = 2a[2][1] = 4a[3][0] = 3a[3][1] = 6a[4][0] = 4a[4][1] = 8

参数数组,通常用于传递未知数量的参数给函数。举例如下:

using System;namespace ArrayApplication{    class ParamArray    {        public int AddElements(params int[] arr)        {            int sum = 0;            foreach(int i in arr)            {                sum += i;            }            return sum;        }    }    class TestClass    {        static void Main(string[] args)        {            ParamArray app = new ParamArray();            int sum = app.AddElements(512,720,250,567,889);            Console.WriteLine("总和是:{0}",sum);            Console.ReadKey();        }    }}

输出如下:

总和是:2938

四、字符串
字符串和C++没差,举例如下:

using System;namespace StringApplication{    class Program    {        static void Main(string[] args)        {            //字符串,字符串连接            string fname,lname;            fname = "Rowan";            lname = "Atkinson";            string fullname = fname + lname;            Console.WriteLine("Full Name: {0}",fullname);            //通过使用string构造函数            char[] letters = {'H','e','l','l','o'};            string greetings = new string(letters);            Console.WriteLine("Greetings: {0}",greetings);            //方法返回字符串            string[] sarray = {"Hello","From","Tutorials","Point"};            string message = String.Join(" ",sarray);            Console.WriteLine("Message: {0}",message);            //用于转化值的格式化方法            DateTime waiting = new DateTime(2012,10,10,17,58,1);            string chat = String.Format("Message sent at {0:t} on {0:D}",waiting);            Console.WriteLine("Message: {0}",chat);            Console.ReadKey();        }    }}

输出如下:

Full Name: RowanAtkinsonGreetings: HelloMessage: Hello From Tutorials PointMessage: Message sent at 17:58 on 20121010

另外,再举一个检测字符串中是否含有另一个字符串的例子:

using System;namespace StringApplication{    class StringProg    {        static void Main(string[] args)        {            string str = "This is test";            if(str.Contains("test"))            {                Console.WriteLine("The sequence 'test' was found.");            }            Console.ReadKey();        }    }}

输出如下:

The sequence 'test' was found.

还有很多字符串的操作,看手册基本就能够学会。

五、继承
C#的继承和C++几乎没啥区别,有一点需要注意,C#不支持多重继承,但是可以用接口来实现多重继承。举例如下:

using System;namespace InheritanceApplication{    class Shape    {           public void setWidth(int w)        {            width = w;        }        public void setHeight(int h)        {            height = h;        }        protected int width;        protected int height;    }    //基类 PaintCost    public interface PaintCost    {        int getCost(int area);    }    //派生类    class Rectangle : Shape,PaintCost    {        public int getArea()        {            return(width * height);        }        public int getCost(int area)        {            return area * 70;        }    }    class RectangleTester    {        static void Main(string[] args)        {            Rectangle Rect = new Rectangle();            int area;            Rect.setWidth(5);            Rect.setHeight(7);            area = Rect.getArea();            //打印对象的面积            Console.WriteLine("总面积: {0}",  Rect.getArea());            Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));            Console.ReadKey();        }    }}

输出结果如下:

总面积: 35油漆总成本: $2450

六、多态
在面向对象里,多态性往往表现为“一个接口,多种功能”。多态性可以是静态的,也可以是动态的。在静态多态性中,函数的响应是在编译时发生,在动态多态性中,函数的响应是在运行时发生。
C#提供了两种技术来实现静态多态性。分别是:
函数重载
运算符重载
和C++无异,这里讲述C#的动态多态性,C#的动态多态性是通过抽象类和虚方法。

C#允许使用abstract创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。关于抽象类有一些规则:
不能创建一个抽象类的实例
不能在一个抽象类外部声明一个抽象方法
通过在类定义面前放置关键字sealed,可以将类声明为密封类。当一个类被声明为sealed时,它不能被继承。抽象类不能被声明为sealed。举例如下:

using System;namespace PolymophismApplication{    abstract class Shape    {        public abstract int area();    }    class Rectangle: Shape    {        private int length;        private int width;        public Rectangle(int a = 0,int b = 0)        {            length = a;            width = b;        }        public override int area()        {            Console.WriteLine("Rectangle 类的面积:");            return (width * length);        }    }    class RectangleTester    {        static void Main(string[] args)        {            Rectangle r = new Rectangle(10,7);            double a = r.area();            Console.WriteLine("面积:{0}",a);            Console.ReadKey();        }    }}

输出如下:

Rectangle 类的面积:面积:70

虚方法的举例如下:

using System;namespace PolymorphismApplication{   class Shape    {      protected int width, height;      public Shape( int a=0, int b=0)      {         width = a;         height = b;      }      public virtual int area()      {         Console.WriteLine("父类的面积:");         return 0;      }   }   class Rectangle: Shape   {      public Rectangle( int a=0, int b=0): base(a, b)      {      }      public override int area ()      {         Console.WriteLine("Rectangle 类的面积:");         return (width * height);       }   }   class Triangle: Shape   {      public Triangle(int a = 0, int b = 0): base(a, b)      {      }      public override int area()      {         Console.WriteLine("Triangle 类的面积:");         return (width * height / 2);       }   }   class Caller   {      public void CallArea(Shape sh)      {         int a;         a = sh.area();         Console.WriteLine("面积: {0}", a);      }   }     class Tester   {      static void Main(string[] args)      {         Caller c = new Caller();         Rectangle r = new Rectangle(10, 7);         Triangle t = new Triangle(10, 5);         c.CallArea(r);         c.CallArea(t);         Console.ReadKey();      }   }}

输出如下:

Rectangle 类的面积:面积: 70Triangle 类的面积:面积: 25
原创粉丝点击