ref struct 的特性:
只能在栈上分配。不可在堆上分配。
不能作为类、普通结构或数组的成员。
不能作为其他 ref struct 的字段,除非该字段被标记为 ref。
不能被装箱或者转换为 Object、ValueType 或 System.Enum。
不能实现接口。
不能被用作闭包变量(也就是不能被捕获到 lambda 表达式或本地函数中)。
public ref struct Point2
{
public int X { get; set; }
public int Y { get; set; }
}
// ref struct
Point2 p2 = new Point2();
p2.X = 100;
p2.Y = 200;
Console.WriteLine($"坐标:{p2.X},{p2.Y}");
ref return
C# 中的 ref return 又称引用返回,它允许一个方法返回对象的引用而不是对象的值。这意味着返回的引用可以用来修改该对象。ref return 在 C# 7.0 中引入,主要用于优化性能,特别是在处理大型结构时,因为它避免了值类型的复制。
// 关注点:
// 1。定义时,方法返回值类型前加ref
// 2。return关键字后添加ref
static ref int GetArrayElement(int index)
{
int[] array = new int[] { 1, 2, 3, 4 };
return ref array[index];
}
// ref return
ref int num2 = ref GetArrayElement(1);
Console.WriteLine(num2);
1378

被折叠的 条评论
为什么被折叠?



