码迷,mamicode.com
首页 > 其他好文 > 详细

C#学习笔记(五)——函数

时间:2014-10-09 13:58:13      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   使用   ar   for   sp   

一、定义和使用函数。

       直接通过例子进行说明吧

class Program
    {
        static void Write()
        {
            Console.WriteLine("Test output from function");
        }

        static void Main(string[] args)
        {
            Write();
            Console.ReadKey();
        }
    }

1、函数的构架

(1)关键字:static 和 void

          static与面向对象的思维有关系,我们在这里先默认每个函数都需要加上这个关键字;

          void即使便是返回值为空的意思。、

(2)函数名后跟圆括号  e.g  Write();

(3)圆括号里面可以有参数,这个放在后面再讨论,

(4)一个要执行的代码块,放在花括号里面。

2、返回值

(1)当函数返回一个值时,可以采用以下两种方式修改函数

a、在函数声明中指定返回值得类型,但不使用关键字void;

b、使用return关键字结束函数的执行,把返回值传送给调用代码。

static <returnType> <functionName>()
{
      ……
      return <returnValue>;
}

(2)return 不一定要放在最后一行,也很经常用于直接跳出函数。

3、参数

(1)当函数接受参数的时候,就必须指定下列内容

a、函数在其定义指定接受的参数列表,以及这些参数的类型;

b、在每个函数调用中匹配的参数列表。

c、其中可以有任意多个参数,每个参数都有一个类型和一个名称,参数用逗号隔开。每个参数都在函数的代码中用作一个变量。

(2)一个demo

namespace Exercise
{
    class Program
    {
        static int MaxValue(int[] intArray)
        {
            int maxVal = intArray[0];
            for(int i=1;i<intArray.Length;i++)
            {
                if(intArray[i]>maxVal)
                {
                    maxVal = intArray[i];
                }
            }
            return maxVal;
        }

        static void Main(string[] args)
        {
            int[] myArray = { 1, 5, 7, 99, 7, 8, 9, 3 };
            int maxVal = MaxValue(myArray);
            Console.WriteLine("The maximum value in myArray is {0}", maxVal);
            Console.ReadKey();
        }
    }
}

运行结果是:

bubuko.com,布布扣

(3)参数匹配

C#学习笔记(五)——函数

标签:style   blog   http   color   io   使用   ar   for   sp   

原文地址:http://www.cnblogs.com/BlueMountain-HaggenDazs/p/4012374.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!