( ! ) Warning: include(): http:// wrapper is disabled in the server configuration by allow_url_include=0 in D:\www\up\CSharp\class03.php on line 20
Call Stack
#TimeMemoryFunctionLocation
10.0000360168{main}( )...\class03.php:0

( ! ) Warning: include(http://pub.houheaven.com/Nav02/Nav_deep2.htm): failed to open stream: no suitable wrapper could be found in D:\www\up\CSharp\class03.php on line 20
Call Stack
#TimeMemoryFunctionLocation
10.0000360168{main}( )...\class03.php:0

( ! ) Warning: include(): Failed opening 'http://pub.houheaven.com/Nav02/Nav_deep2.htm' for inclusion (include_path='.;C:\php\pear') in D:\www\up\CSharp\class03.php on line 20
Call Stack
#TimeMemoryFunctionLocation
10.0000360168{main}( )...\class03.php:0

① 方法的声明

格式:访问修饰符 返回类型 方法名([参数类型 参数名][……]){ …… }

说明:方法的返回类型用于指定方法计算和返回的值的数据类型,可以是任何类型,也可以是引用类型。如果方法不返回值,就需要将返回类型写成void。

实例:打开

[ 源代码 ]

class Example

{

public int add(int a,int b)

{

ruturn a+b;

}

}

……

Example obj=new Example();

Consloe.WriteLine(obj.add(1,2));

② 方法的调用

在类的内部,格式为:方法名(参数列表);

在类的外部,格式为:对象名.方法名(参数列表);

③ 参数传递

按值传递

当调用方法,将实参传递给形参时,实际上是把实参的值复制给了形参。内存中,实参和形参各自的存储空间中都存有相同的值,所以在方法内,对形参进行运算,改变了形参的值后,实参内的数据是不受影响的。

实例:打开

[ 源代码 ]

class Example

{

public int Switch(int x,int y)

{

Console.WriteLine("x={0},y={1}", x, y);

int z;

z=x;

x=y;

y=z;

Console.WriteLine("x={0},y={1}", x, y);

}

}

……

Example obj=new Example();

int a=2,b=5;

Consloe.WriteLine("a={0},b={1}", a, b);

obj.Switch(a,b);

Consloe.WriteLine("a={0},b={1}", a, b);


[ 输出结果 ]

a=2 , b=5

x=2 , y=5

x=5 , y=2

a=2 , b=5

按引用传递

由于方法只能返回一个值,如果需要方法的运行能够改变几个值,可以使用按引用传递参数的方式。

在按引用传递参数的方式下,当调用方法,将实参传递给形参时,不是值传递,而是将实参的引用(内存地址)传递给形参,这样以来,对形参一切操作实际上是对实参的操作,这样实参的值也会跟着改变。


按引用传递分为两类,基本数据类型和类数据类型。

基本数据类型的参数,在形参和实参前使用ref关键字。

实例:打开

[ 源代码 ]

class Example

{

public int Switch(ref int x,ref int y)

{

Console.WriteLine("x={0},y={1}", x, y);

int z;

z=x;

x=y;

y=z;

Console.WriteLine("x={0},y={1}", x, y);

}

}

……

Example obj=new Example();

int a=2,b=5;

Consloe.WriteLine("a={0},b={1}", a, b);

obj.Switch(ref a,ref b);

Consloe.WriteLine("a={0},b={1}", a, b);


[ 输出结果 ]

a=2 , b=5

x=2 , y=5

x=5 , y=2

a=5 , b=2

类数据类型的参数(自定义类生产的对象、系统类String类、系统控件等)及数组类型的参数,默认都是按引用传递的,不需要在参数前添加ref。

实例:打开

[ 源代码 ]

class Example

{

public int Switch(TextBox x,TextBox y)

{

TextBox z=new TextBox();

z.Text=x.Text;

x.Text=y.Text;

y.Text=z.Text;

}

}

……

Example obj=new Example();

obj.Switch(textBox1,textBox2);

④ 方法的重载

说明:方法的重载,是指声明两个以上的同名方法,来实现对不同类型数据的相同处理。

注意1:重载方法的名称一定要相同。

注意2:重载方法的形参个数或形参类型必须不同。

实例:打开

[ 源代码 ]

class Example

{

public int max(int x, int y)

{

return x > y ? x : y;

}

public int max(int x, int y, int z)

{

int t = x > y ? x : y;

return t > z ? t : z;

}

}

……

Example ex=new Example();

Console.WriteLine(ex.max(6,3));

Console.WriteLine(ex.max(5,2,9));

显示框架
显示框架
显示框架
显示框架