1、 方法概述
方法和C 语言中的 函数共享同一个理念。一直以来,我们在用的Main()方法就是个例子。还有上例中 public string doSth() 也是一个方法。其中,public 是 类的修饰符,string 是方法的返回值,也可以 没有返回值,即 void ,doSth 是方法名称。()括号必须有,在括号中可以有参数,如Doctor 类的构造函 数 public Doctor(string name,byte age) 就有两个参数。方
法体则必须用一对{}括起来。
方法的调用,则需要先实例化类,然后调用类的某个方法。上例中Doctor dc=new Doctor();来实例化 了类,然后 dc.doSth() 就是调用了Doctor 类的方法。
在Maim()函数中调用FunctionTest 之前,y 并没有初始化。但其输出结果确实100;因为这样属于引用 传递,值的修改会被保留下来。
在这里例子中,有三个方法functionTest 其参数都不一样。在调用的时候,系统会根据传递的参数自 动选择调用哪个方法的。这就是方法的重载。
在这里注意,重载的条件是,必须参数类型不同,或者参数个数不同。
方法和C 语言中的 函数共享同一个理念。一直以来,我们在用的Main()方法就是个例子。还有上例中 public string doSth() 也是一个方法。其中,public 是 类的修饰符,string 是方法的返回值,也可以 没有返回值,即 void ,doSth 是方法名称。()括号必须有,在括号中可以有参数,如Doctor 类的构造函 数 public Doctor(string name,byte age) 就有两个参数。方
法体则必须用一对{}括起来。
方法的调用,则需要先实例化类,然后调用类的某个方法。上例中Doctor dc=new Doctor();来实例化 了类,然后 dc.doSth() 就是调用了Doctor 类的方法。
如果方法是静态的,即 static,则不需要实例化类,直接使用 类名.方法名 就可以调用了。如上例 中 Console.WriteLine(Doctor.doAnth()); 即是直接调用了静态的doAnth 方法。
2、方法的参数
参数可以通过引用或者值传递 给方法。具体有什么区别呢?
我们来看个例子。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class OneDoctor
{
static void FunctionTest(int[] arr, int x)
{
arr[0] = 100;
x = 10;
}
static void Main(string[] args)
{
int[] arrTemp = { 0, 1, 2, 3, 4 };
int y = 30;
Console.WriteLine(arrTemp[0]); //0
Console.WriteLine(y); //30
FunctionTest(arrTemp, y);
Console.WriteLine(arrTemp[0]); //100
Console.WriteLine(y); //30
Console.ReadKey();
}
}
}
本例的输出结果是0,30,100,30 因为数组是引用类型,在调用方法前后,引用类型的修改会保留下 来,而值类型的修改不会保留下来。
3、ref 参数。
我们把 上例中的方法修改为 static void FunctionTest(int [] arr, ref int x) 这样,调用的时 候也加上 ref 即:functionTest(arrTemp, ref y); 执行后的结果就是0,30,100,10。ref 关键字是强迫参数通过引用传递。
注意:在调用有ref 参数的方法时,必须将参数要传递的参数提前初始化。但在调用out 参数的方法时 ,就不必提前初始化。
4、out 参数
在上例中,我们稍作修改。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class OneDoctor
{
static void FunctionTest(out int x)
{
x = 100;
}
static void Main(string[] args)
{
int y;
FunctionTest(out y);
Console.WriteLine(y);
Console.ReadKey();
}
}
}
在Maim()函数中调用FunctionTest 之前,y 并没有初始化。但其输出结果确实100;因为这样属于引用 传递,值的修改会被保留下来。
5、方法的重载
所谓重载就是指 方法名相同,而参数不同(参数类型,参数个数)看下面一个例子
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication3
{
class Program
{
static int FunctionTest(int x)
{
return x + 100;
}
static string FunctionTest(string str)
{
return str;
}
static int FunctionTest(int x, int y)
{
return x + y;
}
static void Main(string[] args)
{
Console.WriteLine(FunctionTest(10)); //110
Console.WriteLine(FunctionTest("hello world!")); //hello world
Console.WriteLine(FunctionTest(5,20)); //25
Console.ReadKey();
}
}
}
在这里例子中,有三个方法functionTest 其参数都不一样。在调用的时候,系统会根据传递的参数自 动选择调用哪个方法的。这就是方法的重载。
在这里注意,重载的条件是,必须参数类型不同,或者参数个数不同。