【发布时间】:2017-02-05 21:51:17
【问题描述】:
我正在关注this 示例,了解如何处理空对象。这是我在被卡住之前已经走了多远。
ChessPiece.cs
using System.Collections;
using UnityEngine;
public abstract class ChessPiece: MonoBehaviour
{
public int CurrentX{ set; get; }
public int CurrentZ{ set; get; }
public virtual bool[,] PossibleMove()
{
return new bool[8, 8];
}
public virtual bool isNull
{
get{ return false; }
}
public static ChessPiece NewNull()
{
return new GameObject("NullChessPiece").AddComponent<NullChessPiece>();
}
}
// same file
public class NullChessPiece: ChessPiece
{
public override bool isNull
{
get{ return true; }
}
}
Usage
Pawn.cs
using System.Collections;
using UnityEngine;
public class Pawn: ChessPiece
{
public override bool[,] PossibleMove()
{
bool[,] result = new bool[8,8];
// Usage
if(!piece(0, 1).isNull) {
result[CurrentX, CurrentZ + 2] = true;
}
return result;
}
// Each time this function is executed I get NullChessPiece objects
// in my Hierarchy pane and they just keep on adding
// how do I stop this?
private ChessPiece piece(int x, int z)
{
return BoardManager.Instance.ChessPieces[CurrentX + x, CurrentZ + z] ??
ChessPiece.NewNull();
}
}
Just in case you need to see what's going on here
BoardManager.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class BoardManager: MonoBehaviour
{
public static BoardManager Instance{ set; get; }
public ChessPiece[,] ChessPieces{ set; get; }
private void Start()
{
Instance = this;
}
}
GameObject("NullChessPiece").AddComponent<NullChessPiece>() 这部分让我失望。由于示例中没有关于文章中类似的内容。
它正在工作,唯一的问题是我不断收到很多 NullChessPiece 的实例。
//See comments for more info.
【问题讨论】:
-
我不确定是否需要
NullChessPiece。在我看来,只需使用null即可轻松获得您正在寻找的功能。 -
Null Object 的整点是为了彻底消除空检查。由于我只进行了一半,您仍然会看到空检查。理论上我完成后不会有任何空值检查。
-
空检查有什么问题?你对“空对象”所做的事情本质上与你对空检查所做的事情完全相同,只是增加了一堆额外的设置、物流和开销。唯一需要担心“空对象”的情况是当您的数据类型是结构(不能为空)并且您的
ChessPiece是一个类时。你所做的只是为自己做更多的工作。 -
在“空对象”上使用
null的一个好处是,对“空对象”的操作将完成一些难以追踪的令人困惑的错误,而null会只需抛出NullReferenceException,即可准确显示问题出在哪里。 -
据此article null 检查是不必要的。我正在学习这项技术,但我还没有完成。因此,您看不到成品。我可能根本不会使用这种技术,但我想先学习它,以便以后决定是否使用它。同样,如果做得正确,将不会有任何空值检查。请阅读重构教程以了解发生了什么。