1.方法参数
在方法中,对于参数的数量无法确定的时候,就用参数数组
js
class TestClass
{
public void Test(int a)
{
Console.WriteLine(a);
}
public void Test(int a,int b)
{
Console.WriteLine(a);
Console.WriteLine(b);
}
public void Test(int a, int b, int c)
{
Console.WriteLine(a);
Console.WriteLine(b);
Console.WriteLine(c);
}
}
2.参数数组
- 只有一个参数数组,传入的值分别存入数组中,可以不限数量,这里数量为3
- 用foreach循环,把这3个数依次输出出来
- 并将这3个数相加再输出
js
//只有参数数组的情况
class TestClass
{
public void TestMethod1(params int[] a)
{
int num = 0;
foreach (var item in a)
{
num += item;
Console.WriteLine(item);//依次输出1,2,3
}
Console.WriteLine(num);//6
}
}
internal class Program
{
static void Main(string[] args)
{
TestClass testclass = new TestClass();
testclass.TestMethod1(1,2,3);
}
}
- 既一个参数数组,又有参数的时候,a1为第一个传入的值,后面的值依次传入参数数组中
- 用foreach循环,把这后面2个数依次输出出来
- 并将这2个数相加再输出
js
//既有参数数组的情况,又有参数的情况
class TestClass
{
public void TestMethod2(int a1,params int[] a)
{
int num = 0;
foreach (var item in a)
{
num += item;
Console.WriteLine(item);//依次输出2,3
}
Console.WriteLine(num);//5
}
}
internal class Program
{
static void Main(string[] args)
{
TestClass testclass = new TestClass();
testclass.TestMethod2(1,2,3);
}
}
3.可选参数
- 遇到一个参数,我可能会调,可能不会调用,不知道什么时候调用的情况下使用
- 只调用参数的时候,那么就只修改参数的值,可选参数的值不会改变
- 又调用参数,也调用可选参数的时候,不仅修改参数的值,而且还修改可选参数的值
js
class TestClass
{
public void SelectParm(int a, int b = 100)
{
Console.WriteLine($"{a} {b}");
}
}
internal class Program
{
static void Main(string[] args)
{
TestClass testclass = new TestClass();
testclass.SelectParm(1);//1 100
testclass.SelectParm(1,2);//1 2
}
}