引用自动实现的支持字段 属性

Reference to the backing field of auto-implemented property

在 C# 中,自动实现的属性是一件非常方便的事情。然而,尽管它们只是封装了它们的支持字段,但它们仍然不能作为 ref 或 out 参数传递。例如:

public int[] arr { get; private set; } /* Our auto-implemented property */
/* ... */
public void method(int N) { /* A non-static method, can write to this.arr */
    System.Array.Resize<int>(ref this.arr, N); /* Doesn't work! */
}

在这种特定情况下,我们可以通过这样的 hack 来解决问题:

public void method(int N) { /* A non-static method, can write to this.arr */
    int[] temp = this.arr;
    System.Array.Resize<int>(ref temp, N);
    this.arr = temp;
}

有没有更优雅的方法来使用对 C# 中自动实现的 属性 的支持字段的引用?

Is there a more elegant way to use a reference to the backing field of an auto-implemented property in C#?

据我所知,不是。属性是方法,这就是为什么当参数需要其支持字段的类型时不能以这种方式传递它们的原因。

如果您想使用自动属性,您所说的解决方案就是一个解决方案。否则,您将不得不自己定义一个支持字段并让 属性 使用它。

注意:您可以通过反射获得 auto-属性 的支持字段,但这是一个我不会使用的 hacky 解决方案。

来自 MSDN

You can't use the ref and out keywords for the following kinds of methods:

  • Async methods, which you define by using the async modifier.
  • Iterator methods, which include a yield return or yield break statement.
  • Properties are not variables. They are methods, and cannot be passed to ref parameters.