C#之引用局部变量语法(ref local)

ref Particle p = ref _particles[i];

是 C# 的引用局部变量语法(ref local),它的作用是直接引用数组中某一项的内存地址,而不是创建该元素的副本。这在性能敏感或需要原地修改数组元素时非常有用。

 public struct MyStrct
 {
     public int Int;
     public double Double;
 }

public static void Main()
{
MyStrct[] aa = new MyStrct[3];
MyStrct b = aa[0];
b.Int = 100;
Console.WriteLine($"aa[0].Int:{aa[0].Int}");//b是直接复制副本,所以修改b,修改不到aa
aa[0].Int += 3;
Console.WriteLine($"aa[0].Int:{aa[0].Int}");//修改到了,但是这会生产临时副本
//推荐这样使用,直接操作
ref MyStrct c = ref aa[0];
c.Int += 6 ;
Console.WriteLine($"aa[0].Int:{aa[0].Int}");
Console.ReadLine();

}


优点:
效率更高:避免复制结构体数据(Particle 是个结构体,复制成本比类高)。

代码更简洁:省去手动写回数组的步骤,比如 _particles[i] = p;。

posted @ 2025-05-07 23:22  JohnYang819  阅读(28)  评论(0)    收藏  举报