C#基础:ref 参数

作者:微信公众号:【架构师老卢】
8-3 18:7
35

概述:在 C# 中,ref 关键字用于指示方法参数是引用参数。引用参数允许您将对变量的引用作为参数传递给方法,而不是传递变量值的副本。这意味着在方法中对参数所做的任何更改也会影响方法外部的原始变量。例在下面,我们定义了 ref 方法的语法。ref 方法具有 retrun 类型,例如 int、float 或 string,以及一个 methodName,它可以是方法的任何合适名称,我们定义了参数 ref 与第一个 ref keword,然后它将具有任何数据类型,例如 int、string 和参数名称,例如 referenceParameter,在下面的语法中,我们定义了使用此 ref 参数的参数主体,

在 C# 中,ref 关键字用于指示方法参数是引用参数。引用参数允许您将对变量的引用作为参数传递给方法,而不是传递变量值的副本。这意味着在方法中对参数所做的任何更改也会影响方法外部的原始变量。

在下面,我们定义了 ref 方法的语法。ref 方法具有 retrun 类型,例如 int、float 或 string,以及一个 methodName,它可以是方法的任何合适名称,我们定义了参数 ref 与第一个 ref keword,然后它将具有任何数据类型,例如 int、string 和参数名称,例如 referenceParameter,在下面的语法中,我们定义了使用此 ref 参数的参数主体,并将赋值给此 ref 参数。

returnType methodName(parameters, ref dataType referenceParameter)  
{  
// Method body  
// The method assigns a value to referenceParameter  
// ...  
}

ref 参数的基本结构

方法签名:

定义接受 ref 关键字的方法时,请在方法签名中的参数类型之前指定 ref 关键字。

参数传递:

调用该方法时,还必须使用 ref 关键字来指示要传递对变量的引用。

使用简单变量的示例一

在下面的示例中,我们有私有类 Program,这个 Program 类有 Main 入口方法。在 Main 入口方法中,我们定义了 SimpleWithRef 方法,该方法没有任何返回类型,并且具有整数类型 x 的 ref 参数。在 SimpleWithRef 方法的主体中,我们为 x 变量分配了一个值。实际上,我们正在用新的值修改现有的值。在 SimpleWithRef 方法之外,我们声明了一个整数类型 x vaiable,并为此 x 变量赋值了 10 值。我们在调用 SimpleWithRef 方法之前打印 x 变量的值。即通话前的 10 点。在此之后,我们调用 SimpleWithRef 函数,该函数必须具有 ref 关键字,然后是变量名称 x。在此之后,我们再次打印 x 的值。现在,您可以监控 x 参数的原始值在调用后是否发生了变化。现在已经变成了 30 岁。

using System;
public class Program
{
  public static void Main(string[] args)
  {
    void Simple(int y)
    {
      y = 40; //Not Modifies the original 'y' variable
    }
  
  
    void SimpleWithRef(ref int x)
    {
      x = 30; // Modifies the original 'x' variable
    }
  
  
    int x = 10;
    Console.WriteLine("Before call x value is=" + x);
    SimpleWithRef(ref x); // Calling the SimpleWithRef function
    Console.WriteLine("After call x value is=" + x);
    int y = 20;
    Console.WriteLine("Before cal y value is=" + y);
    Simple(y); // Calling the Simple function
    Console.WriteLine("After call y value is=" + y);
  }
}

输出

Before call x value is=10  
After call x value is=30  
Before cal y value is=20  
After call y value is=20

带有类的示例 2

using System;
public class Program
{
    public static void Main(string[] args)
    {
        Fruit objFruit = new Fruit(18, "WaterMelon", true);
        int fieldPrice = objFruit.GetFruitPrice(); // Accessing a field fruit price
        string fieldName = objFruit.GetFruitName(); // Accessing a field fruit name
        bool fieldIsInMarket = objFruit.GetFruitIsInMarket(); // Accessing a field fruit is in market
        
        
        Console.WriteLine("Fruit result before using ref keword");
        Console.WriteLine("Fruit name: " + fieldName + " Fruit price:" + fieldPrice + " Is available in summer :" + fieldIsInMarket);
        
        
        objFruit.SetFruit(ref objFruit.FruitPrice, ref objFruit.FruitName, ref objFruit.FruitIsAvialableInSummer);
        Console.WriteLine("Fruit result after using ref keword without class");
        Console.WriteLine("Fruit name: " + objFruit.FruitName + " Fruit price:" + objFruit.FruitPrice + " Is available in summer :" + objFruit.FruitIsAvialableInSummer);
        
        
        objFruit.SetNewFruit(ref objFruit);
        Console.WriteLine("Fruit result after using ref keword with class");
        Console.WriteLine("Fruit name: " + objFruit.FruitName + " Fruit price:" + objFruit.FruitPrice + " Is available in summer :" + objFruit.FruitIsAvialableInSummer);
    
    
    }
}


public class Fruit
{
  // Fields (attributes or variables)
  public int FruitPrice;
  public string FruitName;
  public bool FruitIsAvialableInSummer;


// Constructor
public Fruit(int price, string name, bool isAvailable)
{
  FruitPrice = price;
  FruitName = name;
  FruitIsAvialableInSummer = isAvailable;
}


// Methods (functions or behaviors)
public int GetFruitPrice()
{
  return FruitPrice;
}


public string GetFruitName()
{
  return FruitName;
}


public bool GetFruitIsInMarket()
{
  return FruitIsAvialableInSummer;
}


public void SetFruit(ref int FruitPrice, ref string FruitName, ref bool FruitIsAvialableInSummer)
{
  FruitPrice = 28;
  FruitName = "Orange";
  FruitIsAvialableInSummer = false;
}


public void SetNewFruit(ref Fruit fruitChange)
{
  fruitChange.FruitPrice = 23;
  fruitChange.FruitName = "Mango";
  fruitChange.FruitIsAvialableInSummer = true;
}
}

输出

Fruit result before using ref keword  
Fruit name: WaterMelon Fruit price:18 Is available in summer :True  
Fruit result after using ref keword without class  
Fruit name: Orange Fruit price:28 Is available in summer :False  
Fruit result after using ref keword with class  
Fruit name: Mamgo Fruit price:23 Is available in summer :True

使用 struct 的示例 3

using System;
public class Program
{
public static void Main(string[] args)
{
Point p1 = new Point(10, 20);
Point p2 = p1; // Copying p1 to p2
p2.SetValuePoint(ref p2);
Console.WriteLine($"p1: {p1}"); // Output: p1: (10, 20)
Console.WriteLine($"p2: {p2}"); // Output: p2: (30, 20)
}
}


public struct Point
{
public int X;
public int Y;
public Point(int x, int y)
{
X = x;
Y = y;
}


public override string ToString()
{
return $"({X}, {Y})";
}


public void SetValuePoint(ref Point p2)
{
p2.X = 30; // Modifying p2
}
}

输出

p1: (10, 20)  
p2: (30, 20)

为什么我们使用 ref 关键字?

1. 修改原始值:

当需要修改原始变量时,将方法的声明范围排除在外。

2. 复制大型数据结构

当您需要将大型数据结构从一个位置传递到另一个位置时。您可以使用 ref kayword 传递这些大数据,以避免在更改所需位置后复制数据。

3. 恢复多个值

当您需要返回多个值时,您可以使用 ref 关键字。

我们可以通过 ref 关键字将变量或类变量的原始值更改为另一个类,因为 ref 关键字构成了变量或类引用类型。

阅读排行