C#-方法(八)


方法是什么
  方法是C#中将一堆代码进行进行重用的机制
  他是在类中实现一种特定功能的代码块,将重复性功能提取出来定义一个新的方法
  这样可以提高代码的复用性,使编写程序更加快捷迅速

方法格式

  访问修饰符 返回类型 方法名称(参数列表)
  {
    方法体;
  }

  方法是在类或结构中声明的,声明时需要访问修饰符、返回类型、方法名称、参数列表、方法体
    访问修饰符:声明方法对另一个类的可见性,如public、protect
    返回类型:方法可以有返回值也可以无返回值,无返回值时为void,有返回值时需要声明返回值得数据类型
    方法名称:方法的标识符,对大小写敏感
    参数列表:使用小括号括起来,跟在方法名称的后面,用来接收和传递方法的数据。可以有也可以无,根据需要确定
    方法主体:方法所执行的指令集合

示例

 1 using System;
 2 
 3 namespace NumberSwap
 4 { 
 5     class NumberManipulator
 6     {
 7         public int swap(ref int x, ref int y)  //返回值为int类型
 8         {
 9             int temp;
10 
11             temp = x;
12             x = y;
13             y = temp;
14 
15             int sum = x + y;
16             return sum;
17         }
18 
19         static void Main(string[] args)
20         {
21             NumberManipulator n = new NumberManipulator();
22 
23             int a = 100;
24             int b = 200;
25 
26             n.swap(ref a, ref b);  //调用方法
27             Console.WriteLine("调用方法swap后a的值:{0}", a);
28             Console.WriteLine("调用方法swap后b的值:{0}", b);
29 
30             Console.WriteLine("两数之和为:{0}", n.swap(ref a, ref b));
31         }
32     }
33 }

  结果

  

方法重载

  方法重载是在一个类中定义多个方法名相同、方法间参数个数和参数顺序不同的方法
  方法重载是让类以统一的方式处理不同类型数据的一种手段
  方法重载定义时有以下四个要求:
    方法名称必须相同
    参数个数必须不同(如果参数个数相同,那么类型必须不同)
    参数类型必须不同
    和返回值无关

示例 

 1 using System;
 2 
 3 namespace Calculator
 4 {
 5     class Program
 6     {
 7         /// <summary>
 8         /// 方法重载:无参
 9         /// </summary>
10         static void overloaded_func()
11         {
12             Console.WriteLine("方法重载,无参");
13         }
14 
15         /// <summary>
16         /// 方法重载:1个整型参数
17         /// </summary>
18         static void overloaded_func(int x)
19         {
20             Console.WriteLine("方法重载,一个整型参数");
21         }
22 
23         /// <summary>
24         /// 方法重载:1个字符串参数
25         /// </summary>
26         static void overloaded_func(string str)
27         {
28             Console.WriteLine("方法重载,一个字符串参数");
29         }
30 
31         /// <summary>
32         /// 方法重载:2个参数
33         /// </summary>
34         static void overloaded_func(int x, string str)
35         {
36             Console.WriteLine("方法重载,两个参数");
37         }
38 
39 
40         static void Main(string[] args)
41         {
42             // 方法重载1
43             overloaded_func();
44             // 方法重载2
45             overloaded_func(1);
46             // 方法重载3
47             overloaded_func(1, "重载");
48         }
49     }
50 }

  结果

  

  

原文地址:https://www.cnblogs.com/tynam/p/9613725.html