输出参数
- 用 out 修饰符声明的形参是输出形参。类似于引用形参,输出形参不创建新的存储位置。相反,输出形参表示的存储位置恰是在该方法调用中作为实参给出的那个变量所表示的存储位置。
- 当形参为输出形参时,方法调用中的相应实参必须由关键字 out 并后接一个与形参类型相同的 variable-reference组成。变量在可以作为输出形参传递之前不一定需要明确赋值,但是在将变量作为输出形参传递的调用之后,该变量被认为是明确赋值的。
- 在方法内部,与局部变量相同,输出形参最初被认为是未赋值的,因而必须在使用它的值之前明确赋值。
- 在方法返回之前,该方法的每个输出形参都必须明确赋值。
- 声明为分部方法或迭代器的方法不能有输出形参。
- 输出形参通常用在需要产生多个返回值的方法中。
值类型
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26Console.WriteLine("Please input first number:"); string arg1 = Console.ReadLine(); double x = 0; bool b1 = double.TryParse(arg1, out x); //TryParse返回值是bool类型,就是告诉你尝试解析是不是成功了。 //而TryParse告诉解析是否成功,则占用了返回值的功能。 //若想获得解析出来的值,就用到了输出参数out x,拿到输出值。 if (b1==false) { Console.WriteLine("Input error!"); return; } Console.WriteLine("Please input second number:"); string arg2 = Console.ReadLine(); double y = 0; bool b2 = double.TryParse(arg2, out y); if (b2 == false) { Console.WriteLine("Input error!"); return; } double z = x + y; Console.WriteLine("{0} + {1} = {2}",x,y,z);
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30class Program { static void Main(string[] args) { double x = 0; bool b1 = DoubleParse.TryParse("2232", out x); if (b1==true) { Console.WriteLine(x+1); } } } class DoubleParse { public static bool TryParse(string input,out double result) //带有输出参数的方法 { try { result = double.Parse(input); return true; } catch { result = 0; return false; } } }
引用类型
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36class Program { static void Main(string[] args) { Student stu = null; bool b = StudentFactory.Create("Tim", 22, out stu); if (b==true) { Console.WriteLine("Student {0},Age is {1}",stu.Name,stu.Age); } } } class Student { public int Age { get; set; } public string Name { get; set; } } class StudentFactory { public static bool Create(string stuName,int stuAge,out Student result) //第三个参数是输出参数,类型是Student类型,如果创建成功,就使用输出参数把创建的实例交还出来 { result = null; if (string.IsNullOrEmpty(stuName)) { return false; } if (stuAge<18 || stuAge>80) { return false; } result = new Student() { Name = stuName, Age = stuAge }; return true; } }
最后
以上就是直率宝贝最近收集整理的关于C#学习笔记 输出参数的全部内容,更多相关C#学习笔记内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复