方法
参数修饰符
无修饰符
参数无修饰符时,值类型传递到方法时,为该参数的副本,在方法内修改,不影响外部的原始数据。除字符串的引用类型传递的为该对象的地址,在方法内修改影响外部的原始数据。字符串的特殊与创建的模式有关系,详细需了解原型模式。
Main
Modifier modifier = new Modifier();
int a = 1;
string b = "123";
Student student = new Student();
student.Id = 2;
student.Name = "Tom";
// 传递参数
modifier.NoModifier(a, b, student);
modifier.Write(a, b, student);
Console.ReadKey();
Modifier.cs
internal class Modifier
{
public void NoModifier(int a, string b, Student student)
{
a = 100;
b = "new";
student.Id = 200;
student.Name = "Lily";
Write(a, b, student);
}
public void Write(int a, string b, Student student)
{
Console.WriteLine($"a:{a}");
Console.WriteLine($"b:{b}-H:{b.GetHashCode()}");
Console.WriteLine($"c:{student.Id}-{student.Name}-H:{student.GetHashCode()}");
}
}
Student.cs
internal class Student
{
public int Id { get; set; }
public string Name { get; set; }
}
带默认值的参数
在声明一个方法时,可以部分或者全部参数带分配默认值,在调用方法的过程中,如果没有对参数进行赋值,那么方法在运行时,使用默认值。可以使用“参数的变量名称:值”的方式对参数进行赋值。
class Program
{
static void Main(string[] args)
{
// 只传入必要参数
ShowMsg("小鸿");
//结果:我是小鸿,今年23岁了,是一名程序猿。
// 传入必要参数以及一个有默认值的参数
ShowMsg("小鸿", 24);
// 结果:我是小鸿,今年24岁了,是一名程序猿。
// 可以使用“参数的变量名称:值”的方式对其进行赋值
ShowMsg("小鸿", job: "软件开发工程师");
// 结果:我是小鸿,今年23岁了,是一名软件开发工程师。
Console.ReadKey();
}
static void ShowMsg(string name, int age=23, string job="程序猿")
{
Console.WriteLine($"我是{name},今年{age}岁了,是一名{job}。");
}
}
out 修饰符
out:输出参数由被调用的方法赋值,如果被调用的方法没有给参数赋值,则出现编译报错。out 的最大用途是一次调用可获得多个返回值。
namespace TestApp1
{
class Program
{
public static int calculateArea(out int x, out int y)
{
// 如果x和y在函数内没有赋值,则会报错
x = 10;
y = 20;
return x * y;
}
static void Main(string[] args)
{
int x = 2, y = 3;
int area = calculateArea(out x, out y);
System.Console.WriteLine("x=" + x + "\ty=" + y + "\t面积是" + area);
// x=10,y=20,area=200
Console.ReadKey();
}
}
}
ref 修饰符
ref:调用者赋值,并且可以由被调用的方法可选重新赋值,参数按引用传递。如果被调用的方法没有给 ref 参数赋值,不会编译报错。
namespace TestApp1
{
class Program
{
public int calculateArea(ref int x,ref int y)
{
y = 20;
return x * y;
}
static void Main(string[] args)
{
// 变量作为方法的ref参数前必须先赋值
int x = 2, y = 3;
int area = calculateArea(x, y);
System.Console.WriteLine("x=" + x + "\ty=" + y + "\t面积是" + area);
// x=2,y=20,area=40
Console.ReadKey();
}
}
}
params 修饰符
params:允许将一组可变数量的参数作为单独的逻辑参数进行传递,方法只能有一个params修饰符,必须是最后一个参数。
namespace TestApp1
{
class Program
{
public static void printList(params int[] numberList )
{
foreach (var item in numberList)
{
Console.Write(item.ToString() + '\t');
}
}
static void Main(string[] args)
{
printList(1,5,4,9,22,31,4,2,6);
Console.ReadKey();
}
}
}