本文为《Illustrated C# 2008》:方法学习总结
注:此书中文版《C#图解教程》把Local Variables翻译成本地变量,scope翻译成有效范围,看着挺别扭的。其实Local Variables局部变量,scope作用域。
1、从C#3.0开始,可以在变量声明的开始部分的显示类型名的位置使用新的关键字var。表示任何可以从初始化的右边推断出的类型。
使用条件:
1)It can only be used with local variables—not with fields.
2)It can only be used when the variable declaration includes an initialization(变量声明和初始化).
3)Once the compiler infers(推断) the type, it is fixed and unchangeable.
2、You cannot declare another local variable with the same name within the scope of the first name regardless of the level of nesting.
3、方法的参数传递
1)值类型参数 (单向值传递):参数类型 参数名
其实参可以是变量或者任何能计算成相应数据类型的表达式
系统为栈里为形参分配内存
注:变量在用作实参前必须被赋值(在作为输出参数时除外)。对于引用类型,变量可以被赋值为一个引用或null。
2)引用类型参数(双向值传递):ref 参数类型 参数名
其实参必须是变量,在用作实参前必须被赋值。如果是引用类型变量,可以赋值为一个引用或者null值。
形参名相当于实参变量的别名,形参变量和实参变量指向同一个存储空间。由此可见,如果在方法内部更改了形参变量的数据值,则同时也修改了实参变量的数据值。(双向值传递)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Swaper
{
public void Swap(ref int x, ref int y)//被调用方,其中x和y是引用型参数
{
Console.WriteLine("形参的值未交换:{0},{1}",x,y);
int temp;
temp = x; x = y; y = temp;
Console.WriteLine("形参的值已交换:{0},{1}",x,y);
}
}
class TestMethod
{
static void Main(string[] args)//调用方,其中实参是a和b的引用
{
Swaper s =new Swaper();
Console.WriteLine("请输入两个整型数:");
int a =Convert.ToInt32(Console.ReadLine());
int b= Convert.ToInt32(Console.ReadLine());
s.Swap(ref a,ref b); //调用并传递参数
Console.WriteLine("实参的值已交换:{0},{1}",a,b);
Console.ReadLine();
}
}
}
|
3)输出参数(反向单向值传递):out 参数类型 参数名
Output parameters are used to pass data from inside the method back out to the calling code. 和引用类型性质一样。
没有必要在方法调用前为实参赋值。
一个方法中可允许有多个输出参数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public static void MyMethod (out int a, out int b)
{
a = 5;b = 6;
}
static void Main()
{
int x, y;
MyMethod(out x, out y);
Console.WriteLine("调用MyMethod之后, x={0},y={1}", x, y);
Console.ReadLine();
}
}
}
|
注意:不能使用输出参数把数据传入方法,下面是错误的做法。
1
2
3
4
|
public void Add2(out int outValue)
{
int var1 = outValue + 2; // Error! Can't read from an output variable
} // before it has been assigned to by the method.
|
4)数组型参数:
把数组作为参数,有两种使用形式:
(1)在形参数组前不添加params修饰符,直接为普通数组。所对应的实参必须是一个数组名。
(2)在形参数组前添加params修饰符,其后一般跟一个一维数组。所对应的实参可以是数组名,也可以是数组元素值的列表。
注意,无论采用哪一种形式,形参数组都不能定义数组长度。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Program
{
public static float Average ( params long[ ] v )
{
long total, i;
for (i = 0, total = 0; i < v.Length; ++i) total += v[i];
return (float)total / v.Length;
}
static void Main()
{
float x = Average(1, 2, 3, 5);
Console.WriteLine("1、2、3、5的平均值为{0}", x);
x = Average(4, 5, 6, 7, 8);
Console.WriteLine("4、5、6、7、8的平均值为{0}", x);
Console.ReadLine();
}
}
|
本人独立博客:http://www.yixin.me 欢迎交流访问