【问题标题】:Is there a way to get a reference to a C# Array element?有没有办法获得对 C# Array 元素的引用?
【发布时间】:2021-07-05 21:35:37
【问题描述】:

我想知道是否有办法在 c# 中获取对数组元素的引用。

类似这样的东西,但没有指针:

SomeClass *arr[5];
...    
SomeClass** p = &arr[2];

到目前为止,我得到了这个:

SomeClass arr[] = new SomeClass[5];
// Put something in the array
SomeClass p = arr[2]; // This will give me the initial object, not the array ref
p = new SomeClass(); // I want the array to now use this new object

【问题讨论】:

  • 如果SomeClass是一个引用类型,那么你在arr[2]有一个对对象的引用,并且改变p的属性将改变arr[2]中的相同属性。跨度>
  • 我将编辑问题以更好地解释问题
  • 没有指针就无法做到这一点
  • 为什么要将此字段设为字段?听起来像一个XY问题。如果您只是想要一种“获取和设置SomeClass”的方法,则可以存储Func<SomeClass>Action<SomeClass>

标签: c# arrays pointers ref


【解决方案1】:

这不是你想要的吗?

var arr = new SomeClass[5];
ref SomeClass p = ref arr[2];
p = new SomeClass();

【讨论】:

  • 是的,但是有没有办法将p 声明为成员变量?
  • @AntoineGagnon 这样做很不安全,所以你必须使用指针。
  • @AntoineGagnon ref 存在于堆栈中。这就是 C# 确保生命周期的方式。虽然,您可以将数组设为字段,然后在每次需要时使用 ref
猜你喜欢
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 2015-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多