【问题标题】:C# boolean are not saved when updated on Object在 Object 上更新时不保存 C# 布尔值
【发布时间】:2017-05-11 01:49:20
【问题描述】:

---在第一个代码上发现许多错误后更新---

我在对象上的布尔值有一些问题。 这是我的包含 Zone 结构的 Chunk 类:

using System;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        new Chunk();
    }
}

public class Chunk {
  List <Zone> zones;
  public Chunk() {
    // Create 3 elements on the List
    this.zones = new List<Zone>();
    this.zones.Add(new Zone(1));
    this.zones.Add(new Zone(2));
    this.zones.Add(new Zone(42));

    // Add coord to 2th zones
    this.zones[0].AddCoord(1);
    Console.WriteLine("Count : " + this.zones[0].coords.Count); // -> Count: 1

    // Now with bool - NOT WORKING
    this.zones[0].SetBool();
    Console.WriteLine("Bool: " + this.zones[0].isOnChunkBorder ); // -> Bool: False

    // Now with bool - WORKING
    this.zones[0] = this.zones[0].SetBoolAndReturnThis();
    Console.WriteLine("Bool: " + this.zones[0].isOnChunkBorder ); // -> Bool: True
  } 

  public struct Zone {
    public bool isOnChunkBorder;
    public List<int> coords;

    public Zone(int firstCoord) {
      this.coords = new List<int>();
      this.coords.Add(firstCoord);
      this.isOnChunkBorder = false;
    }
    public void AddCoord(int coord) {
      this.coords.Add(coord);
    }
    public void SetBool() {
      this.isOnChunkBorder = true;
    }
    public Zone SetBoolAndReturnThis() {
      this.isOnChunkBorder = true;
      return this;
    }
  }
}

我不知道为什么当我使用简单更新时 struct boolean 没有更新,但是如果 Zone 被 Class 替换或者如果返回 struct 则可以正常工作?

【问题讨论】:

  • 我们如何运行您的代码来自己查看?请提供一个完整的可运行且语法正确的示例。
  • 在我修复了一堆语法错误之后 - 我看不到你正在解释的行为:ideone.com/eKZpRm 这实际上是提供可运行示例的原因,而不是快速制作的示例,因为有机会当它变得与你实际拥有的相差太大时,你过于简单化了。
  • 你不需要把你的整个代码放在这里。只需创建一个演示问题的最小示例。例如,您有很多代码引用了一些名为i 的变量,但它没有在任何地方定义。出于演示目的,您可以将其更改为 01...
  • 没有。如果我添加了 MISSING using 指令,它不会编译:error CS0246: The type or namespace name `Vecor2' could not be found. Are you missing an assembly reference? 请提供一个示例,可以复制粘贴并运行无需任何更改。跨度>
  • "我不知道如何在没有整个 Unity 项目的情况下运行 C# 代码" --- 在此处运行:ideone.com 或此处dotnetfiddle.net

标签: c# oop unity3d


【解决方案1】:

Zone 是一个结构体引起的你观察到的效果。

结构是value types,并在分配时复制。

【讨论】:

  • 好的,但我不明白为什么它与 List update 一起使用?
  • @Arthur 因为新结构被创建并返回给你,然后你使用它。
猜你喜欢
  • 1970-01-01
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 2021-10-26
相关资源
最近更新 更多