一、方法的定义与调用
1. 定义
方法一般写在一个类中,格式如下:
访问修饰符 返回值类型 方法的名字 (参数列表)
{
这个方法的代码块
}
访问修饰符一般先记住public
,返回值类型void
表示无返回值,方法的名字一般以大驼峰命名。
2. 调用
在方法名字后面加上()
,()
称为执行运算符。方法中的代码会在被调用时执行,执行完毕后回到调用位置继续执行外部代码。
例如:
Console.WriteLine(1);
Test();
Console.WriteLine(2);
// 练习:封装一个方法,在控制台输出 10 次吴亦凡
MyWrite();
Console.WriteLine("------------");
MyWrite();
二、方法的参数
1. 参数的概念
- 形参:形式参数,方法定义时声明在
()
里面的变量,其值由实参决定。 - 实参:实际参数,方法调用时写在
()
中的数据,将赋值给对应的形参。
通过传递参数,可以控制一个方法做出不同的功能。
2. 参数的默认值
在方法定义时,可以给形参设置默认值。当方法调用时未传递该参数,则使用默认值。可选参数必须写在必选参数后面。
例如:
public static void MyWrite(int count, string str = "劣迹明星")
{
for (int i = 0; i < count; i++)
{
Console.WriteLine(str);
}
}
三、方法参数的赋值
1. 值传递(值参数)
方法默认的传递方式。当传递基本数据类型时,方法内部修改形参不会影响外部;当传递引用类型时,会影响外部。
2. 引用传递(引用参数)
当传递基本数据类型时,方法内部修改形参会影响外部。当方法内部需要修改传递进来的变量时,使用引用传递。
例如:
int x = 2;
Test(ref x); // 传递参数时加上 ref 关键字
Console.WriteLine("x:" + x);
int a = 666, b = 888;
Huan(ref a, ref b);
Console.WriteLine(a);
Console.WriteLine(b);
public static void Test(ref int a)
{
Console.WriteLine("参数:" + a);
a = 20;
}
public static void Huan(ref int x, ref int y)
{
(x, y) = (y, x);
}
四、引用传参
方法传递参数有值传递和引用传递两种方式。
- 值传递:实参的值会赋值给方法执行时声明的新变量,传递基本数据类型时,方法内部修改形参不影响外部,传递引用类型时会影响外部。
- 引用传递:传递变量本身,当方法内部修改形参时,外部会受到影响。
五、方法的返回值
有些方法以计算为主要目标,执行结束后需要获取计算结果,此时需要在定义方法的位置指定返回值类型,没有返回值写void
。
例如:
public static string Test()
{
return "罗志祥";
}
public static int Sum(int a, int b)
{
return a + b;
}
六、out 输出参数
ref
是输入关键字,out
是输出关键字。return
只能返回一个数据,若需要同时返回多个数据,可使用输出参数out
。
out
和ref
的区别:
out
传递参数可以不用赋值,但在方法中必须赋值;ref
传递的参数在传入时必须赋值。ref
主要作用是传入数据,out
主要作用是传出数据,且out
传递的参数只能在赋值后取值。
例如:
int a = 1;
int b = 2;
Test1(ref a, ref b);
Console.WriteLine($"a=={a},b=={b}");
int c;
int d;
Test2(out c, out d);
Console.WriteLine($"c=={c},d=={d}");
public static void Test1(ref int x, ref int y)
{
Console.WriteLine($"Test1方法中x:{x},y{y}");
x = 20;
y = 30;
}
public static void Test2(out int x, out int y)
{
x = 20;
y = 30;
Console.WriteLine($"Test2方法中x:{x},y{y}");
}
七、参数列表
一个方法可以接收未知数量的参数,通过params
关键字实现。
例如:
public static int Sum(params int[] nums)
{
int sum = 0;
for (int i = 0; i < nums.Length; i++)
{
Console.WriteLine(nums[i]);
sum += nums[i];
}
return sum;
}
public static void Test(int a, string b, bool c, params string[] strs)
{
// 演示
}
八、作用域
作用域是一个变量可以使用的范围,局部作用域中声明的变量仅在某个代码块中生效。
例如:
int a = 1;
// 从这里开始能访问a------
Console.WriteLine(a);
// 从这里结束不能访问a------
public static void Test1()
{
}