总目录
C# 语法总目录
参考链接:
C#语法系列:C# 语言类型(一)—预定义类型值之数值类型
C#语法系列:C# 语言类型(二)—预定义类型之字符串及字符类型简述
C#语法系列:C# 语言类型(三)—数组/枚举类型/结构体
C#语法系列:C# 语言类型(四)—传递参数及其修饰符
C#语法系列:C# 语言类型(五)—其他
C# 语言类型 四—传递参数及其修饰符
- 传递参数及其修饰符
- 1. 按值传递参数
- 2. ref 修饰符
- ref引用局部变量
- ref 引用返回值
- 3. out 修饰符
- 4. params 修饰符
- 5. 可选参数
- 6. 命名参数
- 7.隐式类型变量var
传递参数及其修饰符
1. 按值传递参数
C#方法中的参数默认是按照值传递
2. ref 修饰符
ref 修饰符 用于将 数值类型参数 进行引用传递
namespace _036_ref 修饰符 {
class Program {
static void Func(ref int a,ref int b)
{
int temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
int a = 10;
int b = 20;
Func(ref a, ref b);
Console.WriteLine(a.ToString()); //20
Console.WriteLine(b.ToString()); //10
}
}
}
namespace _036_ref 修饰符 {
class Program {
static void Func(ref string a,ref string b)
{
string temp = a;
a = b;
b = temp;
}
static void Main(string[] args)
{
string a = "hello";
string b = "nihao";
Func(ref a,ref b);
Console.WriteLine(a.ToString()); //nihao
Console.WriteLine(b.ToString()); //hello
}
}
}
ref引用局部变量
需要C#7
int[] a = { 1, 2, 3 };
ref int b = ref a[1];
Console.WriteLine(a[1]);
b = 5;
Console.WriteLine(a[1]);
//输出
2
5
ref 引用返回值
需要C#7
static string a = "abc";
static ref string Method()
{
return ref a;
}
static void Main(string[] args)
{
ref string c = ref Method();
Console.WriteLine(a);
c = "hhh";
Console.WriteLine(a);
}
//输出
abc
hhh
3. out 修饰符
out 修饰符是传出参数,用于将方法内的数值用参数的形式传出,此外,带 out 修饰的参数,在方法结束前必须对它进行赋值。
namespace _036_out 修饰符 {
class Program {
static void Func(string a,out string b,out int c)
{
b = a;
c = 1;
}
static void Main(string[] args)
{
string a = "hello";
string b = "nihao";
//如果不想要传出参数,那么就用下划线 _ 代替
Func(a,out b,out _);
Console.WriteLine(a.ToString()); //hello
Console.WriteLine(b.ToString()); //hello
}
}
}
如果不想要其他的out参数,那么在调用方法的时候 用下划线 _ 代替,这叫做丢弃变量
//声明
static void Func(string a,out string b,out int c)
//调用
Func(a,out b,out _);
4. params 修饰符
params 修饰的参数必须是一维数组,这个参数必须是最后一个参数
namespace _036_params 修饰符 {
class Program {
static void Func(string a,params int[] c)
{
int sum = 0;
foreach(var i in c)
{
sum += i;
}
Console.WriteLine(sum.ToString());
}
static void Main(string[] args)
{
Func("",1,2,3); //6
}
}
}
5. 可选参数
可选参数就是给方法中 的形参添加一个默认值
void Func(string a = "fast",int[] c)
6. 命名参数
命名参数就是不管函数声明中参数的顺序,在调用过程中指定给哪个形参赋值。
此外命名参数还可以和值传递的混合使用,但是命名参数必须放在末尾。
还有可选参数和命名参数可以混合使用。
namespace _036_命名参数 {
class Program {
static void Func(int a,int b)
{
Console.WriteLine(a);
Console.WriteLine(b);
}
static void Main(string[] args)
{
int c = 1;
int d = 2;
Func(b:d, a:c);
}
}
}
7.隐式类型变量var
var a = "abc";
//等同于
string a = "abc";
//没有任何区别
总目录
C# 语法总目录
参考链接:
C#语法系列:C# 语言类型(一)—预定义类型值之数值类型
C#语法系列:C# 语言类型(二)—预定义类型之字符串及字符类型简述
C#语法系列:C# 语言类型(三)—数组/枚举类型/结构体
C#语法系列:C# 语言类型(四)—传递参数及其修饰符
C#语法系列:C# 语言类型(五)—其他