obsidian/笔记文件/2.笔记/params 用法简介.md
2025-03-26 00:02:56 +08:00

94 lines
2.1 KiB
Markdown
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#unity/日常积累
# C# params 用法简介
params 是C#的关键字 可变长参数,是在声明方法时参数类型或者个数不确定时使用
关于params 参数数组,需掌握以下几点:
一.参数数组必须是一维数组  
二.不允许将params修饰符与ref和out修饰符组合起来使用   
三.与参数数组对应的实参可以是同一类型的数组名,也可以是任意多个与该数组的元素属于同一类型的变量  
四.若实参是数组则按引用传递,若实参是变量或表达式则按值传递
五.形式为方法修饰符 返回类型 方法名params 类型[ ] 变量名)
六.params参数必须是参数表的最后一个参数
代码:
``` cs
namespace ConsoleApp1
{
class Program
{
static void Main()
{
UseParams(1, 2, 3); //既可以用任意多个int
int[] myarray = new int[3] { 10, 11, 12 };
UseParams(myarray); //也可以是int一维数组
UseParams2(1, 'a', new object() );
}
public static void UseParams(params int[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
public static void UseParams2(params object[] list)
{
for (int i = 0; i < list.Length; i++)
{
Console.WriteLine(list[i]);
}
Console.WriteLine();
}
}
}
```
![[Pasted image 20240329121106.png]]
 当然如果要实现多种类型可以使用object
``` cs
static void main()
{
UsrParam("123",1);
}
public void UsrParam(params Object[] objlist)
{
Console.WriteLine(objlist[0]);
Console.WriteLine(objlist[1]);
}
```
如果前面是特定类型后面是params也可以
但是注意不能把指定类型参数放在params参数后面因为无法解析也没有意义
``` cs
static void main()
{
UsrParam(12.33,"123",1);
}
public void UsrParam(double x , params Object[] objlist)
{
Console.WriteLine(x);
Console.WriteLine(objlist[0]);
Console.WriteLine(objlist[1]);
}
```