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

Min*_*s97 3 c# properties reference backing-field

在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! */
}
Run Code Online (Sandbox Code Playgroud)

在这个特定的情况下,我们可以解决这个问题:

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Ond*_*cek 6

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

据我所知,事实并非如此.属性是方法,这就是当参数需要一种类型的支持字段时,不能以这种方式传递它们的原因.

如果要使用自动属性,您所描述的解决方案是一种解决方案.否则,您必须自己定义一个支持字段并让属性使用它.

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