第六章 函数
本章内容:
- 如何定义和使用不接受或返回任何数据的简单函数
- 如何在函数中传入传出数据
- 使用变量作用域
- 如何结合使用Main()函数和命令行参数
- 如何把函数提供为结构类型的成员
- 如何使用函数重载
- 如何使用委托
6.1 定义和使用函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static void Write()
{
Console.WriteLine("Text output from function.");
}
static void Main(string[] args)
{
Write();
Console.ReadKey();
}
}
}
一般采用PascalCase形式编写函数名。
6.1.1 返回值
当函数返回一个值时,可以采用以下两种方式修改函数:
- 在函数声明中指定返回值的类型,但不使用关键字void
- 使用return关键字结束函数的执行,把返回值传递给调用代码
6.1.2 参数
当函数接受参数时,就必须指定下述内容:
- 函数在其定义中指定要接受的参数列表,以及这些参数的类型
- 在每个函数调用中匹配的参数列表
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static int MaxValue(int[] intArray)
{
int maxValue = intArray[0];
for (int i = 1; i < intArray.Length; i++)
{
if (intArray[i] > maxValue)
maxValue = intArray[i];
}
return maxValue;
}
static void Main(string[] args)
{
int[] myArray = { 1,8,3,6,2,5,9,3,0,2};
int maxValue = MaxValue(myArray);
Console.WriteLine("The maximum value in myArray is {0}",maxValue);
Console.ReadKey();
}
}
}
参数数组:C#允许为函数指定一个特定的参数(只能指定一个),这个参数必须是函数定义中的最后一个参数,成为参数数组。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static int SumVals(params int[] vals)
{
int sum = 0;
foreach (int val in vals)
{
sum += val;
}
return sum;
}
static void Main(string[] args)
{
int sum = SumVals(1,5,2,9,8);
Console.WriteLine("Summed valueds is {0}",sum);
Console.ReadKey();
}
}
}
引用参数和值参数:ref关键字,用作ref关键字的变量有两个限制:
- 首先,函数可能会改变引用参数的值,所以必须在函数调用中使用“非常量”变量。
- 其次,必须使用初始化过的变量
输出参数:out关键字,执行方式与ref关键字是相同的,但是有一些重要的区别:
- 把未赋值的变量用作ref参数是非法的,但可以把未赋值的变量用作out参数
- 在函数使用out参数时,out参数必须看作是还未赋值
6.2 变量的作用域
局部变量,全局变量(static关键字)
6.2.1 其他结构中变量的作用域
6.2.2 参数和返回值与全局变量
6.3 Main()函数
Main()函数是C#程序的入口点,执行这个函数就是执行应用程序。
这个函数可以返回void或int,有一个可选参数string[] args。
Main()函数可以使用以下四种版本:
- static void Main()
- static void Main(string[] args)
- static int Main()
- static int Main(string[] args)
6.4 结构函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
struct CustomerName
{
public string firstName, lastName;
public string Name()
{
return firstName + " " + lastName;
}
}
static void Main(string[] args)
{
CustomerName myCustomer;
myCustomer.firstName = "John";
myCustomer.lastName = "Franklin";
Console.WriteLine(myCustomer.Name());
Console.ReadKey();
}
}
}
6.5 函数的重载
函数重载允许创建多个同名函数,这些函数可能使用不同的参数类型。
6.6 委托
委托是一种可以把引用存储为函数的类型。
委托的声明非常类似于函数,但不带函数体,要使用delegate关键字。
委托的声明指定了一个返回类型和一个参数列表。