【问题标题】:How to make it possible to assign value to an array, while making it Impossible to assign each of the array elements individually?如何使为数组赋值成为可能,同时又不可能单独分配每个数组元素?
【发布时间】:2019-08-07 16:05:14
【问题描述】:

我正在开发一个 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.
  }
}

我怎样才能让客户端将数组分配给我的成员变量,但阻止他为数组中的单个元素分配值?

【问题讨论】:

  • 如果对于我们这些不想麻烦安装 Unity3d 环境的人,您可以提供有关您正在尝试的 Unity3d 场景的更多详细信息,您可以扩大您的问题的受众范围去效仿。具体来说:当你说它“不可能”时,确切是什么意思?你有错误吗?运行?编译时?更新顶点值是否没有任何效果? Mesh 类及其 vertices 成员的 Unity3d 声明是什么?那是一个领域吗?财产?
  • 基于源代码here。看起来它可能会在您每次访问 vertices 时创建一个新数组,这意味着更新该数组实际上不会更新 Mesh 对象内的任何内容。所以如果你做了public int[] Grades { get { var r = new int[grades.Length]; grades.CopyTo(r, 0); return r;} set { grades = value; } },那可能会得到你想要的行为。
  • 太棒了。谢谢!
  • 为什么我被否决了?

标签: c# arrays unity3d properties indexer


【解决方案1】:

如果您不想直接访问 set 元素,请将其设为私有字段并提供设置数组的方法。如果您愿意,您还可以提供一种方法来返回数组的副本作为单独的引用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 2011-08-19
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    • 2022-12-30
    • 1970-01-01
    • 2013-01-29
    相关资源
    最近更新 更多