【发布时间】:2009-12-13 00:33:51
【问题描述】:
我正在开发一款游戏的玩家库存系统。
我有一个结构 Slot,它有一个 List
我想表达的是,Slot 可以限制它可以包含的 Loot 子类。例如,如果 Slot 代表一个弹药容器,我希望它只包含作为弹药容器的 Loot 子类,例如“Quivers”和“Shot Pouches”(这将子类 Container 沿线某处)。
战利品类
public abstract class Loot : GameEntity, ILootable
{
public int MaxUnitsPerStack { get; set; }
public int MaxUnitsCarriable { get; set; }
public int MaxUnitsOwnable { get; set; }
public void Stack() { }
public void Split() { }
public void Scrap() { }
}
容器类
public abstract class Container : Loot
{
public List<Slot> Slots { get; set; }
public Container(int slots)
{
this.Slots = new List<Slot>(slots);
}
}
插槽结构
public struct Slot
{
public Loot Content;
public int Count;
public List<Loot> ExclusiveLootTypes;
public Slot(Loot[] exclusiveLootTypes)
{
this.Content = null;
this.Count = 0;
List<Loot> newList;
if (exclusiveLootTypes.Count() > 0)
{
newList = new List<Loot>(exclusiveLootTypes.Count());
foreach (Loot l in exclusiveLootTypes)
{
newList.Add(l);
}
}
else { newList = new List<Loot>(); }
this.ExclusiveLootTypes = newList;
}
}
玩家库存
public struct PlayerInventory
{
static Dictionary<Slot, string> Slots;
static void Main()
{
Slots = new Dictionary<Slot, string>();
/* Add a bunch of slots */
Slots.Add(new Slot(/* I don't know the
syntax for this:
Quiver, Backpack */), "Backpack"); // Container
}
}
我不知道如何在 PlayerInventory 类的 Main 方法中的 Slot 构造函数调用中为 Loot 子类提供参数。
我希望这很清楚。提前致谢。
编辑
我能够使用 David Sieler 的方法和一些反射解决这个问题(我的意思是让它编译)。
插槽结构
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
public struct Slot
{
private Loot _content;
private int _count;
public List ExclusiveLootTypes;
public Loot Content
{
get { return _content; }
private set
{
if ((ExclusiveLootTypes.Contains(value.GetType())) && (value.GetType().IsSubclassOf(Type.GetType("Loot"))))
{
_content = value;
}
}
}
public int Count
{
get { return _count; }
set { _count = value; }
}
public Slot(params Type[] exclusiveLootTypes)
{
this._content = null;
this._count = 0;
List newList;
if (exclusiveLootTypes.Count() > 0)
{
newList = new List(exclusiveLootTypes.Count());
foreach (Type l in exclusiveLootTypes)
{
newList.Add(l);
}
}
else { newList = new List(); }
this.ExclusiveLootTypes = newList;
}
}
PlayerInventory 调用 Slot 构造函数
Slots.Add(new Slot(typeof(Backpack)));
再次感谢大家的讨论。
【问题讨论】:
-
只考虑了一天,Loot 实例代表了一种战利品。插槽本身有一个 Count 属性,表示它包含多少它所持有的战利品。我完全希望改变这个十几次,但这就是它目前的工作方式。不错的 TES 参考 :)
-
对不起,我删除了询问
Loot实例是否代表一种战利品或实际战利品的评论,因为我忘记了我在写它时的想法。因此,您似乎只需将可能的战利品类型传递给Slot构造函数,如@Anon 的答案所示,尽管可能有很多类型的战利品可以放置在背包。你有没有想过一个界面可以让各种战利品实现可以放在背包里? -
嗯,ExclusiveLootTypes 列表代表了对插槽内容的一组约束,而不是可能的内容范围。如果该列表有任何条目,则该插槽只能包含列表中类型的项目。但是,如果列表为空,则它可以包含任何内容。我还没有写出那个例程,但这就是我的想法。所有的战利品子类都可以放在一个背包里——这是让它们“战利品”的原因之一。
-
但是你不能把魔神短剑放在箭袋里。 ...
List<Loot>看起来很像一个可能是插槽内容的战利品类型列表,不是吗? -
确实如此。你认为这是我可以通过对该属性进行适当评论来解决的问题吗?还是它表明了一些更根本的缺陷?
标签: c# constructor types constraints subclassing