Skip to content

Instantly share code, notes, and snippets.

@stilllisisi
Last active March 11, 2020 08:43
Show Gist options
  • Save stilllisisi/a417838804a1445609278dbf7dfaedf2 to your computer and use it in GitHub Desktop.
Save stilllisisi/a417838804a1445609278dbf7dfaedf2 to your computer and use it in GitHub Desktop.
【C#-参数】C#参数修饰符、可变参数、可选参数
//out
//out修饰的参数必须是变量, 在函数体内必需进行赋值, 且必须在参数使用前赋值
//因此在调用函数传参时,out修饰的参数值是用不到的, 可以不对其赋值, 传入函数体后, 要先赋值再使用
void ParameOut(out int value)
{
value = 0;
}
//ref
//ref修饰的参数必须是变量, 在函数内部可以先使用该参数, 再修改参数值或不改变参数值
//因此在调用函数传参前必需赋值
void ParameRef(ref int value)
{
Debug.Log(value);
value++;
Debug.Log(value);
}
//可变参数/params
//可以传入多个类型相同, 但数量不固定的参数
//params修饰的参数必须是一维数组
//可传入多个参数, 无参数时默认传入长度为0的数组
//可传入数组 (如果传入null, 函数内部需要判断空值)
//params修饰的参数必须是最后一个参数, 同样一个函数也只能有一个params修饰的参数
void ParameMore(int value01, params int[] values)
{
string str = value01.ToString();
if (values != null)
{
for (int i = 0; i < values.Length; i++)
{
str += " " + values[i];
}
}
Debug.Log(str);
}
//可选参数/默认参数
//形参设置默认值, 函数调用时可以不传递该参数, 采用该默认值, 如果传参, 则使用实参
//可选参数必须在必需参数之后, 可选参数可以有多个
//利用可选参数可以实现类似函数重载
void ParameDefault(int value01, int value02 = 2, string value03 = "three")
{
string str = value01 + " " + value02 + " " + value03;
Debug.Log(str);
}
//调用
void Start()
{
//调用
int tmpValue01;
ParameOut(out tmpValue01);
int tmpValue02 = 2;
ParameRef(ref tmpValue02);
int[] array = { 0, 1, 2, 3, 4, 5 };
ParameMore(1, array);
ParameMore(1);
ParameMore(1, null);
ParameMore(1, 2, 3);
ParameDefault(1, 2);
}
@stilllisisi
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment