C#入门(二)

方法

按引用传递参数

引用参数是一个对变量的内存位置的引用。当按引用传递参数时,与值参数不同的是,它不会为这些参数创建一个新的存储位置。引用参数表示与提供给方法的实际参数具有相同的内存位置。

在 C# 中,使用 ref 关键字声明引用参数。

using System;

namespace ConsoleApp1
{
    class Program
    {
        public void swap(ref int x, ref int y)
        {
            int temp;

            temp = x; /* 保存 x 的值 */
            x = y;    /* 把 y 赋值给 x */
            y = temp; /* 把 temp 赋值给 y */
        }

        static void Main(string[] args)
        {
            Program n = new Program();
            /* 局部变量定义 */
            int a = 100;
            int b = 200;

            Console.WriteLine("在交换之前,a 的值: {0}", a);
            Console.WriteLine("在交换之前,b 的值: {0}", b);

            /* 调用函数来交换值 */
            n.swap(ref a, ref b);

            Console.WriteLine("在交换之后,a 的值: {0}", a);
            Console.WriteLine("在交换之后,b 的值: {0}", b);

            Console.ReadLine();

        }
    }
}

 

按输出传递参数

return 语句可用于只从函数中返回一个值。但是,可以使用 输出参数 来从函数中返回两个值。输出参数会把方法输出的数据赋给自己,其他方面与引用参数相似。

 

using System;

namespace ConsoleApp1
{
    class Program
    {
        public void getValue(out int x)
        {
            x = 1;
        }

        static void Main(string[] args)
        {
            Program n = new Program();
            /* 局部变量定义 */
            int a = 100;

            Console.WriteLine("在方法调用之前,a 的值: {0}", a);

            /* 调用函数来获取值 */
            n.getValue(out a);

            Console.WriteLine("在方法调用之后,a 的值: {0}", a);
            Console.ReadLine();

        }
    }
}

 

可空类型

C# 可空类型(Nullable)

 ? : 单问号用于对 int,double,bool 等无法直接赋值为 null 的数据类型进行 null 的赋值,意思是这个数据类型是 NullAble 类型的。

int? i = 3 
等同于
Nullable<int> i = new Nullable<int>(3);

int i; //默认值0
int? ii; //默认值null

 

Null 合并运算符( ?? )

Null 合并运算符用于定义可空类型和引用类型的默认值。Null 合并运算符为类型转换定义了一个预设值,以防可空类型的值为 Null。Null 合并运算符把操作数类型隐式转换为另一个可空(或不可空)的值类型的操作数的类型。

如果第一个操作数的值为 null,则运算符返回第二个操作数的值,否则返回第一个操作数的值。

using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            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);
            Console.ReadLine();

        }
    }
}

 

 

String 

String 类有许多方法用于 string 对象的操作。下面的表格提供了一些最常用的方法:

序号方法名称 & 描述
1public static int Compare( string strA, string strB ) 
比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。
2public static int Compare( string strA, string strB, bool ignoreCase ) 
比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。但是,如果布尔参数为真时,该方法不区分大小写。
3public static string Concat( string str0, string str1 ) 
连接两个 string 对象。
6public bool Contains( string value ) 
返回一个表示指定 string 对象是否出现在字符串中的值。
7public static string Copy( string str ) 
创建一个与指定字符串具有相同值的新的 String 对象。
8public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count ) 
从 string 对象的指定位置开始复制指定数量的字符到 Unicode 字符数组中的指定位置。
9public bool EndsWith( string value ) 
判断 string 对象的结尾是否匹配指定的字符串。
10public bool Equals( string value ) 
判断当前的 string 对象是否与指定的 string 对象具有相同的值。
11public static bool Equals( string a, string b ) 
判断两个指定的 string 对象是否具有相同的值。
12public static string Format( string format, Object arg0 ) 
把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。
13public int IndexOf( char value ) 
返回指定 Unicode 字符在当前字符串中第一次出现的索引,索引从 0 开始。
14public int IndexOf( string value ) 
返回指定字符串在该实例中第一次出现的索引,索引从 0 开始。
15public int IndexOf( char value, int startIndex ) 
返回指定 Unicode 字符从该字符串中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
16public int IndexOf( string value, int startIndex ) 
返回指定字符串从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
17public int IndexOfAny( char[] anyOf ) 
返回某一个指定的 Unicode 字符数组中任意字符在该实例中第一次出现的索引,索引从 0 开始。
18public int IndexOfAny( char[] anyOf, int startIndex ) 
返回某一个指定的 Unicode 字符数组中任意字符从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
19public string Insert( int startIndex, string value ) 
返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置。
20public static bool IsNullOrEmpty( string value ) 
指示指定的字符串是否为 null 或者是否为一个空的字符串。
21public static string Join( string separator, string[] value ) 
连接一个字符串数组中的所有元素,使用指定的分隔符分隔每个元素。
22public static string Join( string separator, string[] value, int startIndex, int count ) 
连接接一个字符串数组中的指定位置开始的指定元素,使用指定的分隔符分隔每个元素。
23public int LastIndexOf( char value ) 
返回指定 Unicode 字符在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
24public int LastIndexOf( string value ) 
返回指定字符串在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
25public string Remove( int startIndex ) 
移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。
26public string Remove( int startIndex, int count ) 
从当前字符串的指定位置开始移除指定数量的字符,并返回字符串。
27public string Replace( char oldChar, char newChar ) 
把当前 string 对象中,所有指定的 Unicode 字符替换为另一个指定的 Unicode 字符,并返回新的字符串。
28public string Replace( string oldValue, string newValue ) 
把当前 string 对象中,所有指定的字符串替换为另一个指定的字符串,并返回新的字符串。
29public string[] Split( params char[] separator ) 
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。
30public string[] Split( char[] separator, int count ) 
返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。int 参数指定要返回的子字符串的最大数目。
31public bool StartsWith( string value ) 
判断字符串实例的开头是否匹配指定的字符串。
32public char[] ToCharArray()
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。
33public char[] ToCharArray( int startIndex, int length ) 
返回一个带有当前 string 对象中所有字符的 Unicode 字符数组,从指定的索引开始,直到指定的长度为止。
34public string ToLower()
把字符串转换为小写并返回。
35public string ToUpper()
把字符串转换为大写并返回。
36public string Trim()
移除当前 String 对象中的所有前导空白字符和后置空白字符。

 

结构体(Struct)

在 C# 中,结构体是值类型数据结构。它使得一个单一变量可以存储各种数据类型的相关数据。struct 关键字用于创建结构体。

结构体是用来代表一个记录。

C# 结构的特点

在 C# 中的结构与传统的 C 或 C++ 中的结构不同。C# 中的结构有以下特点:

  • 结构可带有方法、字段、索引、属性、运算符方法和事件。
  • 结构可定义构造函数,但不能定义析构函数。但是,您不能为结构定义无参构造函数。无参构造函数(默认)是自动定义的,且不能被改变。
  • 与类不同,结构不能继承其他的结构或类。
  • 结构不能作为其他结构或类的基础结构。
  • 结构可实现一个或多个接口。
  • 结构成员不能指定为 abstract、virtual 或 protected。
  • 当您使用 New 操作符创建一个结构对象时,会调用适当的构造函数来创建结构。与类不同,结构可以不使用 New 操作符即可被实例化。
  • 如果不使用 New 操作符,只有在所有的字段都被初始化之后,字段才被赋值,对象才被使用。

 

继承

基类的初始化

using System;
namespace RectangleApplication
{
    class Rectangle
    {
        // 成员变量
        protected double length;
        protected double width;
        public Rectangle(double l, double w)
        {
            length = l;
            width = w;
        }
    }
    class Tabletop : Rectangle
    {
        public Tabletop(double l, double w) : base(l, w)
        { }
    }

}

 

接口

多重继承指的是一个类别可以同时从多于一个父类继承行为与特征的功能。与单一继承相对,单一继承指一个类别只可以继承自一个父类。

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

接口使用 interface 关键字声明,它与类的声明类似。接口声明默认是 public 的。

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;
        }
    }

}

多态

抽象类

C# 允许您使用关键字 abstract 创建抽象类,用于提供接口的部分类的实现。当一个派生类继承自该抽象类时,实现即完成。抽象类包含抽象方法,抽象方法可被派生类实现。派生类具有更专业的功能。

请注意,下面是有关抽象类的一些规则:

  • 您不能创建一个抽象类的实例。
  • 您不能在一个抽象类外部声明一个抽象方法。
  • 通过在类定义前面放置关键字 sealed,可以将类声明为密封类。当一个类被声明为 sealed 时,它不能被继承。抽象类不能被声明为 sealed。
using System;
namespace PolymorphismApplication
{
   abstract class Shape
   {
       abstract public 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();
      }
   }
}

虚方法

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

虚方法是使用关键字 virtual 声明的。

虚方法可以在不同的继承类中有不同的实现。

对虚方法的调用是在运行时发生的。

动态多态性是通过 抽象类 和 虚方法 实现的。

using System;
using System.Collections.Generic;

public class Shape
{
    public int X { get; private set; }
    public int Y { get; private set; }
    public int Height { get; set; }
    public int Width { get; set; }
   
    // 虚方法
    public virtual void Draw()
    {
        Console.WriteLine("执行基类的画图任务");
    }
}

class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("画一个圆形");
        base.Draw();
    }
}
class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("画一个长方形");
        base.Draw();
    }
}
class Triangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("画一个三角形");
        base.Draw();
    }
}

class Program
{
    static void Main(string[] args)
    {
        // 创建一个 List<Shape> 对象,并向该对象添加 Circle、Triangle 和 Rectangle
        var shapes = new List<Shape>
        {
            new Rectangle(),
            new Triangle(),
            new Circle()
        };

        // 使用 foreach 循环对该列表的派生类进行循环访问,并对其中的每个 Shape 对象调用 Draw 方法 
        foreach (var shape in shapes)
        {
            shape.Draw();
        }

        Console.WriteLine("按下任意键退出。");
        Console.ReadKey();
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值