簡體   English   中英

如何不可能為數組分配值,同時又不可能分別分配每個數組元素呢?

[英]How to make it possible to assign value to an array, while making it Impossible to assign each of the array elements individually?

我正在研究Unity3D項目並使用Mesh類,
Mesh類內部,有一個成員變量Vector3[] vertices
現在,可以通過以下方式設置mesh.vertices

Vector3[] v = new Vector3[3];
v[0] = new Vector3[0,0,0];
v[1] = new Vector3[1,1,1];
v[2] = new Vector3[2,2,2];
mesh.vertices = v; 

設置單個元素,如下所示: mesh.vertices[0] = new Vector3(1,1,1)似乎無效。
(同樣, mesh.vertices[0].x = 5也無效)。
當我說沒有效果時,我的意思是代碼確實可以編譯並且沒有錯誤地運行,但是數組的元素沒有改變。
由於頂點表示一個表面,因此設計師希望所有頂點都一起更改似乎是合乎邏輯的。

我試圖用簡單的代碼來模仿這種神奇的功能,但無濟於事。
我想念什么?
與屬性有關嗎?
索引器?
一些奇怪的組合?

class Student
{
  private int[] grades = {92, 99, 96};
  public int[] Grades{
      get{
          Console.WriteLine("getter: ");
          return grades;
      }
      set{
          Console.WriteLine("setter: ");
          grades = value;
      }
  }
}

class HelloWorld
{
  static void Main ()
  {
    int[] low_grades = {53, 51, 55};
    Student student = new Student();
    student.Grades = low_grades; // This assignment is possible and this is O.K.
    student.Grades[0] = 52;  // This assignment is Possible and this is NOT O.K.
  }
}

我如何才能使客戶端為我的成員變量分配一個數組,但是阻止他為數組中的各個元素分配值呢?

如果您不想直接訪問set元素,請將其設置為私有字段,並提供設置數組的方法。 如果需要,還可以提供一種方法來返回數組的副本作為單獨的引用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM