简体   繁体   English

如何不可能为数组分配值,同时又不可能分别分配每个数组元素呢?

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

I m working on a Unity3D project and using the Mesh class, 我正在研究Unity3D项目并使用Mesh类,
inside the Mesh class there is a member variable Vector3[] vertices . Mesh类内部,有一个成员变量Vector3[] vertices
Now, while setting mesh.vertices in the following way is possible 现在,可以通过以下方式设置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; 

setting an individual element, like this: mesh.vertices[0] = new Vector3(1,1,1) seems to have no effect. 设置单个元素,如下所示: mesh.vertices[0] = new Vector3(1,1,1)似乎无效。
(also, mesh.vertices[0].x = 5 have no effect as well). (同样, mesh.vertices[0].x = 5也无效)。
When i say no effect i mean that the code does compile and run with no errors, but the elements of the array are not changing. 当我说没有效果时,我的意思是代码确实可以编译并且没有错误地运行,但是数组的元素没有改变。
Since the vertices represent a surface, It seems logical that the designer wanted for all them to be changed together. 由于顶点表示一个表面,因此设计师希望所有顶点都一起更改似乎是合乎逻辑的。

I have tried to mimic this magical functionality with a simple code to no avail. 我试图用简单的代码来模仿这种神奇的功能,但无济于事。
What am i missing? 我想念什么?
Is it something with Properties? 与属性有关吗?
Indexers? 索引器?
Some weird combination? 一些奇怪的组合?

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.
  }
}

How can i make it possible for the client to assign an array to my member variable, but to stop him from assigning values to individual elements in the array? 我如何才能使客户端为我的成员变量分配一个数组,但是阻止他为数组中的各个元素分配值呢?

If you don't want direct access to set elements, make it a private field and provide a method to set the array. 如果您不想直接访问set元素,请将其设置为私有字段,并提供设置数组的方法。 If you want you can also provide a method to return a copy of the array as a separate reference. 如果需要,还可以提供一种方法来返回数组的副本作为单独的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM