C# basics ⑧-method (function, overload, out, ref)

table of Contents

1. What is a method (function)?

2. What are the benefits of using methods?

3. Grammar:

Four, actual combat drills

        Five, the difference between ref and out parameter transfer

①, out of mass participation:

② The transfer of ref:

        Six, method overload


image.png

 

1. What is a method (function)?

A function is a mechanism for reusing a bunch of codes (that is, putting the reused code in a method, whoever wants to use the adjustment will do.)

Compare it to a function. It is likened to a bicycle production boss who puts screws in one place, wheels in one place, and bicycle chains in one place. Whatever needs to be assembled can be taken from the warehouse. Perform their duties.

 

2. What are the benefits of using methods?

Easy to modify, increase readability, reusability, encapsulation

 

3. Grammar:

Access modifier static return type method name (parameter list)


Four, actual combat drills

①. The user is asked to enter two numbers to determine the maximum value of the two numbers

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("请输入第一个数");                    //输入第一个数
        int number1 = Convert.ToInt32(Console.ReadLine());    //接收用户输入内容,并转换为int类型

        Console.WriteLine("请输入第二个数");                    //输入第二个数
        int number2 = Convert.ToInt32(Console.ReadLine());    //接收并转换为int类型

        int max =  Show(number1, number2);                    //调用Show()这个方法,有两个返回值
        Console.WriteLine("最大的数是:{0}", max);             //输出结果
        Console.ReadKey();
    }
    /// <summary>
    /// 此方法用来比较两个数的大小,返回的是最大值
    /// </summary>
    /// <param name="num1">用来比较的第一个数</param>
    /// <param name="num2">用来比较的第二个数</param>
    /// <returns>返回的是最大值</returns>
    public static int Show(int num1, int num2)               //static静态方法,方法名Show,有参数有返回值
    {
        int number=num1> num2 ? num1 : num2;                //判断两个数的大小
        return number;                                      //返回结果
    }
}

② Take the largest integer, smallest integer, sum, and average value from an integer array

class Program
{
    static void Main(string[] args)
    {
        int[] nums = new int[] { 1,2,3,4,5,6};        //定义一个int类型的数组nums
        ArrayNumbers(nums);                           //调用ArrayNumbers这个有参数的方法,
        Console.ReadKey();    
    }
    public static void ArrayNumbers(int[] num)        //方法
    {
        int max = int.MinValue;                       //定义一个变量max,用于判断最大值
        int min = int.MaxValue;                       //定义一个变量min,用于判断最小值
        int sum = 0;                                  //定义一个整数变量,初始值为0

        for (int i = 0; i < num.Length; i++)          //遍历num这个数组
        {
            if (num[i] > max)                         //如果遍历的这个值>最大值
            {
                max = num[i];                         //把这个值赋给变量max
            }
            if (num[i] < min)                         //如果遍历的这个值<最大值
            {
                min = num[i];                         //把这个值赋给变量min
            }
            sum += num[i];                            //求和
        }
        Console.WriteLine("最大值为:{0},最小值为{1},和为{2},平均分为{3}", max, min, sum, sum / num.Length);     //在控制台输出结果
    }
}

③, calculate the sum of all the elements of an integer array

class Program
{
    static void Main(string[] args)
    {
        int[] nums = new int[] { 1, 2, 3, 4, 5, 6 };         //定义一个整型数组nums
        int sum = ArraySum(nums);                            //调用方法ArraySum
        Console.WriteLine("和为:{0}",sum);                  //在控制台输出结果
        Console.ReadKey();           
    }
    public static int ArraySum(int[] num)                   //有返回值的整型方法
    {
        int sum = 0;                                        //变量,求和
        for(int i = 0; i < num.Length; i++)                 //遍历num这个数组
        {
            sum += num[i];                                  //对数组元素的和进行累加
        }
        return sum;                                         //返回
    }
}

④. The names of people in the array are divided into: For example: Bella|Edward|Jacob...

class Program
{
    static void Main(string[] args)
    {        
        string[] names = new string[] { "贝拉", "爱德华", "雅各布","安妮" };   //string类型数组names
        ArrayNames(names);                                                   //调用ArrayNames这个方法
        Console.ReadKey();                                                   
    }
    public static void ArrayNames (string[] name)                             //方法
    {
        string str = "";                                                      //定义一个string类型变量,用于盛放添加字符之后的字符串
        for (int i = 0; i < name.Length-1; i++)                               //遍历数组,
        {
            str += name[i] + "|";                                            //循环给每个元素后面加“|”
        }
        Console.WriteLine(str+name[name.Length-1]);                          //输出变换后的字符串
    }
}

⑤, each element of an integer array is processed as follows:

If the element is positive, the value of the element at this position is +1;

If the element is negative, the value of the element at this position is -1;

If the element is 0, it remains unchanged

class Program
{
    static void Main(string[] args)
    {
        int[] nums = new int[] { 1, 2, 3, 4, 5, 6 };        //定义一个int型变量nums
        ArrayNumber(nums);                                  //调用ArrayNumber这个方法
        Console.ReadKey();
    }
    public static void ArrayNumber(int[] num)               //方法
    {
        for(int i = 0; i< num.Length; i++)                  //遍历进行判断
        {
        if(num[i] > 0)                                      //如果这个元素>0
        {
            num[i]++;                                       //+1
        }
        if (num[i] < 0)                                     //如果这个元素<0
        {
            num[i]--;                                       //—1
        }                
        }
        for (int i = 0; i < num.Length; i++)                //遍历数组num
        {
            Console.Write(num[i] + "\t");                   //在控制台输出结果
        }
    }            
}

⑥, reverse the order of the elements of a string array

{"I", "Yes", "Good people"}{"Good people", "Yes", "I"}. Exchange the i-th and length-i-1th

class Program
{
    static void Main(string[] args)
    {
        string[] str = new string[] { "我", "是", "好人" };          //定义一个string类型变量
        ArrayForr(str);                                             //调用ArrayForr这个方法
        Console.ReadKey();
    }
    public static void ArrayForr(string[] num)                      //static静态方法,无返回值
    {
        Array.Sort(num);                                            //Array类,用于对数组元素进行排序
        for (int i = 0; i < num.Length; i++)
        {
            Console.Write(num[i] + "\t");                           //在控制台输出结果
        }
    }
}

 


Five, the difference between ref and out parameter transfer

 

out

ref

Assign initial value (in the method body)

have to

Not necessarily (initial value is assigned in the method, but the initial value is not assigned to Main; no initial value is assigned in the method, and the initial value must be assigned to Main)

The value used when calling

From within the method

Initial value assigned in the method: the value in the method is used without initial value assigned in the method: the value in the Main function is used

transfer

Method name (out parameter)

Method name (ref parameter)

①. Passing parameters of out:

 

② The transfer of ref:

The first case: no initial value is assigned to the method body

The second case: the initial value is assigned to the method body


Six, method overload

The same two are different (the method name is the same, the number of parameters is different, and the type is different)

①, judge whether a number entered is a prime number

//质数,除了1和它自身外,不能被其他自然数整除的数

Console.WriteLine("请输入一个数");                   //在控制台提示输入数字
int numb = Convert.ToInt32(Console.ReadLine());     //接收用户输入的内容
bool result = ZhiShu(numb);                         //定义bool类型的变量,接收调用ZhiShu方法传回来的内容
string shu = result == true ? "是质数" : "不是质数"; //判断是不是质数
Console.WriteLine(shu);                             //在控制台输出
Console.ReadKey();

public static bool ZhiShu(int number)
{
	for (int i = 2; i < number; i++)               //for循环,2是最小的质数
	{
		if (number % i == 0)                       //如果输入的这个数和i整除=0
		{
			return false;                          //则返回false,不是质数
		}
	}
	return true;                                   //否则,返回true,是质数
}

②. Use methods to realize the int type, find the maximum and minimum values

int[] numbers = { 1, 2, 3, 4, 5, 6, 7 };      //定义numbers数组并且赋初值
int max;                                      //最大值
int min;                                      //最小值
FirstNumber(numbers, out max, out min);      //调用FirstNumber方法,
Console.WriteLine("最大值为{0}", max);        //输出最大值结果
Console.WriteLine("最小值为{0}", min);        //输出最小值结果
Console.ReadKey();

public static void FirstNumber(int[] nums, out int first, out int last)
{
	first = int.MinValue;                    //最大值
	last = int.MaxValue;                     //最小值
	for (int i = 0; i < nums.Length; i++)    //for循环
	{
		if (nums[i] > first)                 //如果数字>最大值
		{
			first = nums[i];                 //最大值
		}
		if (nums[i] < last)                  //如果数字<最大值
		{ 
			last = nums[i];                  //最小值
		} 
	}
}

③. Realize the function of MyTryParse, find the maximum and minimum values

Console.WriteLine("请输入一个数字");
string strNumber = Console.ReadLine();
int num;
bool result = Program.MyTryParse(strNumber, out num);
bool result1 = int.TryParse(strNumber, out num);

public static bool MyTryParse(string s, out int result)   //此方法中有out参数,所以需要给它赋初值
{
	result = 0;
	try                                                   //try catch语句
	{
		result = Convert.ToInt32(s);   
		return true;
	}
	catch
	{
		return false;
	}
}

④, the user can only enter a number between 0 and 100 to write a method, otherwise the prompt is out of range

Console.WriteLine("请输入1-100之间数字");      //提示用户输入
bool result = GetNumber(Console.ReadLine());  //接收用户输入内容,调用GetNumber方法判断输入是否在范围内
if (result )                                 //如果范围为true
{
	Console.WriteLine("在范围内");            //在范围内
}
else                                         //否则
{
	Console.WriteLine("不在范围内");          //不在范围内
} 
public static bool GetNumber(string str)    //判断用户输入的数字范围是否正确
{
	int number = OutNumber(str);            //调用OutNumber方法,判断输入
	if (number >= 0 && number < 100)        //如果输入的数字在0-100之间
	{
	return true;    //则返回true
	}
	else                //否则
	{
	return false;   //返回false
	}
}
public static int OutNumber(string s)          //此方法中有out参数,所以需要给它赋初值
{
	while (true)
	{
		try               //try catch语句
		{
			int number = Convert.ToInt32(s);   //将接收到的内容转换为int类型                
			return number;                     //如果可以转换为int类型,则返回数值
		}
		catch                                  //如果报异常
		{
			Console.WriteLine("输入错误,请重新输入");
			s = Console.ReadLine();
		}
	}
}

 

Guess you like

Origin blog.csdn.net/weixin_43319713/article/details/109265216