我有两个类:ItemAmmunition 和 ItemConsumables。它们的工作方式相同,但主要区别在于 ItemAmmunition 可以放置在 MainCell 和 AmmunitionCell 中,而 ItemConsumables 只能放置在 MainCell 中。这就是所有问题的开始!
MainCell 中的非工作代码。
public void OnDrop(PointerEventData eventData)
{
var a = eventData.pointerDrag.GetComponent<ItemConsumables>();
if (eventData.pointerDrag.GetComponent<ItemConsumables>() != null)
a = eventData.pointerDrag.GetComponent<ItemConsumables>();
else
a = eventData.pointerDrag.GetComponent<ItemAmmunition>();
if (CheckCellFree(this, a.size))
{
a.prevMainCell = this;
a.SetPosition(a.gameObject, this, null);
CellOccupation(this, false, dragItem.size);
}
else
{
dragItem.SetPosition(dragItem.gameObject, dragItem.prevMainCell, null);
CellOccupation(dragItem.prevMainCell, false, dragItem.size);
}
}
我什至无法正常找出其中包含的内容并写下来!如果我像这样执行此代码(第一个代码,但已被我更正。):
public void OnDrop(PointerEventData eventData)
{
if (eventData.pointerDrag.GetComponent<ItemConsumables>() != null)
{
var a = eventData.pointerDrag.GetComponent<ItemConsumables>();
if (CheckCellFree(this, a.size))
{
a.prevMainCell = this;
a.SetPosition(a.gameObject, this, null);
CellOccupation(this, false, a.size);
}
else
{
dragItem.SetPosition(a.gameObject, a.prevMainCell, null);
CellOccupation(a.prevMainCell, false, a.size);
}
}
else
{
var a = eventData.pointerDrag.GetComponent<ItemAmmunition>();
if (CheckCellFree(this, a.size))
{
a.prevMainCell = this;
a.SetPosition(a.gameObject, this, null);
CellOccupation(this, false, a.size);
}
else
{
dragItem.SetPosition(a.gameObject, a.prevMainCell, null);
CellOccupation(a.prevMainCell, false, a.size);
}
}
}
事实证明这很长!我已经为此苦苦挣扎了很长时间。如何缩短这些 if-else 语句,以及一般如何分配这些变量?我不想发明自行车。
据我了解,我们正在讨论第二段代码。您需要阅读有关概括的内容。
但为了泛化,您需要这些类
ItemConsumables
都ItemAmmunition
具有共同的继承者或实现具有您所需的公共成员的共同接口。由于我没有看到类,也无法从代码中理解类型,因此无法准确描述接口。我想你可以自己添加。
接下来,表明类实现了这个接口
结果会是这样的