引用参数用于引用变量的内存位置。与需要新存储位置的值参数不同,引用参数表示与作为参数传递给方法的原始参数相同的内存位置。在C#中,我们使用关键字“ref”来声明引用参数。当我们将引用参数作为参数传递给 C# 中的函数时,我们传递的是对内存位置的引用而不是原始值。我们在 C# 中将此概念称为“按引用调用”。
语法
ref data_typevariable_name
其中 data_type 是变量名称为变量的数据类型。
下面给出的是提到的示例:
演示按引用调用的 C# 程序,其中我们计算数字的平方并在按引用调用函数之前和调用函数之后显示值。
代码:
using System; //a namespace called program1 is defined namespace program1 { //a class called check is defined class check { //a function is defined which takes reference variable as an argument public void displaypower(ref double value) { //the square of the passed value is found using pow method double power = Math.Pow(value,2); //The resulting value is added to the value passed as reference value = value + power; Console.WriteLine("Value when the control is inside the function "+value); } //main method is called static void Main(string[] args) { //a double variable is defined double value = 5; //an instance of the check class is defined which consists of the function taking reference parameter as an argument check check1 = new check(); Console.WriteLine("Value before the function is called "+value); //a function is called by reference check1.displaypower(ref value); Console.WriteLine("The value of the variable remains the same as inside the function because we are calling the function by reference " + value); } } }
输出:
说明:
演示按引用调用的 C# 程序,其中我们通过引用调用函数并将小写字母字符串作为引用参数传递,将给定的小写字母字符串转换为大写字母。
代码:
using System; //a namespace called program1 is defined namespace program1 { //a class called check is defined class check { //a function is defined which takes reference variable as an argument public void displayupper(ref string value) { //ToUpper method is used to convert the string from small letters to capital letters value = value.ToUpper(); Console.WriteLine("Value when the control is inside the function "+value); } //main method is called static void Main(string[] args) { //a double variable is defined string value = "shobha"; //an instance of the check class is defined which consists of the function taking reference parameter as an argument check check1 = new check(); Console.WriteLine("Value before the function is called "+value); //a function is called by reference check1.displayupper(ref value); Console.WriteLine("The value of the variable remains the same as inside the function because we are calling the function by reference " + value); } } }
输出:
说明:
推荐文章
这是 C# Call By Reference 的指南。在这里,我们通过工作和编程示例来讨论介绍。您还可以查看以下文章以了解更多信息 –
以上是C# 通过引用调用的详细内容。更多信息请关注PHP中文网其他相关文章!