C#参数传递
来源:互联网 发布:赚淘宝运费险犯法吗 编辑:程序博客网 时间:2024/06/08 00:03
在 C# 中,有三种向方法传递参数的方式:
按值传递参数
这是参数传递的默认方式。在这种方式下,当调用一个方法时,会为每个值参数创建一个新的存储位置。
实际参数的值会复制给形参,实参和形参使用的是两个不同内存中的值。
所以,当形参的值发生改变时,不会影响实参的值,从而保证了实参数据的安全。
按引用传递参数
引用参数是一个对变量的内存位置的引用。当按引用传递参数时,与值参数不同的是,它不会为这些参数创建一个新的存储位置。引用参数表示与提供给方法的实际参数具有相同的内存位置。
在 C# 中,使用 ref 关键字声明引用参数。
按值传递、按引用传递参数函数实例
using System;namespace CalculatorApplication{ class NumberManipulator { public void swap_value(int x, int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 temp 赋值给 y */ } public void swap_ref(ref int x, ref int y) { int temp; temp = x; /* 保存 x 的值 */ x = y; /* 把 y 赋值给 x */ y = temp; /* 把 temp 赋值给 y */ } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int b = 200; Console.WriteLine("在交换之前\n"); Console.WriteLine("a 的值: {0}", a); Console.WriteLine("b 的值: {0}", b); /* 调用按值传递函数来交换值 */ n.swap_value(a, b); Console.WriteLine("在调用按值传递函数交换之后\n"); Console.WriteLine("a 的值: {0}", a); Console.WriteLine("b 的值: {0}", b); /* 调用按引用传递函数来交换值 */ n.swap_ref(ref a, ref b); Console.WriteLine("在调用按值传递函数交换之后\n"); Console.WriteLine("a 的值: {0}", a); Console.WriteLine("b 的值: {0}", b); Console.ReadLine(); } }}
编译运行结果如下:
按输出传递参数
在 C# 中,使用out 关键字声明输出传递参数。
仅作为输出,不能作为输入参数。
using System;namespace CalculatorApplication{ class NumberManipulator { public void getValue(out int x, int indata ) { int temp = 5; x = temp*indata; } static void Main(string[] args) { NumberManipulator n = new NumberManipulator(); /* 局部变量定义 */ int a = 100; int indata = 200; Console.WriteLine("在方法调用之前,a 的值: {0}", a); /* 调用函数来获取值 */ n.getValue(out a, indata); Console.WriteLine("在方法调用之后,a 的值: {0}", a); Console.ReadLine(); } }}
编译执行结果如下:
0 0
- C#中的参数传递
- C#中的参数传递
- C#中的参数传递
- C#的参数传递
- C#多线程参数传递
- C#多线程参数传递
- C#多线程参数传递
- c#参数传递
- c# 参数传递类型
- C# 参数传递
- C# 多线程 参数传递
- C#中的参数传递
- C#中的参数传递
- C#参数传递方式
- c#参数传递
- C# 参数传递
- C#参数传递详解
- C#参数传递
- 浅谈UBOOT
- python 中的 数组 矩阵 列表
- 统计字符
- 顺利提升软件项目规划效果的十种方式
- Spring中ClassPathXmlApplicationContext类的简单使用(转)
- C#参数传递
- Java的引用和C++的指针的区别
- 数论求逆元的三种方法
- VIM plugin management
- sublime text3 插件
- RandomAccess 接口使用
- Spring Bean的初始化和销毁方式详解(转载)
- leetcode81. Search in Rotated Sorted Array II
- Mat类中的rowRange和colRange的用法