zoukankan      html  css  js  c++  java
  • 方法

    为什么要使用方法(函数):

    我们将一些常出现的代码,尤其是用来实现某些特定的功能的代码,我们把它封装起来,就有了我们的方法。

    函数就是将一堆代码进行复用的一种机制

    方法的语法:

    [访问修饰符]  static   [返回值类型]   方法名([参数列表])

    {

    方法体;

    }

    方法要定义在类中

    调用方法:

    1、第一种 如果是静态方法(由static修饰的)则调用类名.方法名();

    2、如果跟Main()函数在一个类中,Program,那么可以直接写方法名调用。

    Return

    1、返回要返回的值

    2、退出所在方法

    在Main()方法中调用Test()方法,我们管Main()方法叫做调用者,管Test()方法,叫做被调用者。

    如果被调用者想得到调用者的值:

    2个方法:

    1、在Main()方法外,Program类下,声明一个静态的字段。这个字段可以被Program类中所有的方法都访问到。

    2、传参数。

    如果调用者想得到被调用者的值的时候呢?

    使用返回值,步骤。

    1、首先你要确定返回值的类型

    2、把void改成对应的类型

    3、最后不要忘记在方法中return 返回值。

    一个方法只能有一个返回值

    当形参是数组的时候,我们传数组名

     1   static void Main(string[] args)
     2         {
     3             Console.WriteLine("你确定要关机吗?");
     4             string s=Anwer();
     5             if (s == "y")
     6             {
     7                 Console.WriteLine("关机");
     8             }
     9             else
    10             {
    11                 Console.WriteLine("不关机");
    12             }
    13             Console.ReadKey();
    14         }
    15         public static string Anwer()
    16         {
    17             string result = "";
    18             do
    19             {
    20                 result=Console.ReadLine();
    21                 if (result != "y" && result != "n")
    22                 {
    23                     Console.WriteLine("请重新输入");
    24                 }
    25             }while(result!="y"&&result!="n");
    26             return result;
    27         }
    返回值实例
     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5             Console.WriteLine("请输入a值");
     6             int a = Convert.ToInt32(Console.ReadLine());
     7             Console.WriteLine("请输入b值");
     8             int b = Convert.ToInt32(Console.ReadLine());
     9             int result=Number(a, b);
    10             Console.WriteLine("平均值为{0}",result/2);
    11             Console.ReadKey();
    12         }
    13         static int Number(int a,int b)
    14         {
    15             return a + b;
    16         }
    17     }
    参数和返回值实例
  • 相关阅读:
    关于三次握手与四次挥手你要知道这些
    seafile看不见repo报500错误的解决方法
    VMWare Workstation 配置docker多macvlan网络方法
    利用Python3的dpkt库进行ARP扫描
    关于LAMP配置Let’s Encrypt SSL证书
    OpenSSL生成CA证书及终端用户证书
    CentOS7.2安装Vim8和YouCompleteMe
    CentOS 7.2安装Jenkins自动构建Git项目
    CentOS 7.2 安装Gerrit 2.14.6
    CentOS7.2编译GCC7.3
  • 原文地址:https://www.cnblogs.com/kongbei2013/p/3257365.html
Copyright © 2011-2022 走看看