我正在创建一个游戏,目前正在为它开发库存系统。我有一个代表玩家的类,它看起来像这样:
class Player {
public Weapon WeaponSlot {get;set;}
public Shield ShieldSlot {get;set;}
//etc.
}
武器、盾牌等是通用 Item 类的子类:
class Item {
//...
}
class Weapon : Item {
//...
}
还有Weapon等的子类,但这并不重要。
无论如何,我正在创建一个 UserControl 来显示/修改给定库存槽的内容。但是,我不确定该怎么做。在 C++ 中,我会使用类似的东西:
new InventorySlot(&(player.WeaponSlot));
但是,我不能在 C# 中这样做。
我找到了 TypedReference 结构,但这不起作用,因为不允许您使用这些结构之一创建字段,所以我无法存储它以供以后在控件中使用。
反射是唯一的方法吗,还是有其他一些我不知道的工具?
编辑----
作为引用,这是我所做的:
partial class InventorySlot : UserControl {
PropertyInfo slot;
object target;
public InventorySlot(object target, string field) {
slot = target.GetType().GetProperty(field);
if (!slot.PropertyType.IsSubclassOf(typeof(Item)) && !slot.PropertyType.Equals(typeof(Item))) throw new //omitted for berevity
this.target = target;
InitializeComponent();
}
//...
}
而且,它是这样初始化的:
new InventorySlot(player, "WeaponSlot");
此外,关于性能,我不太关心。这不是实时游戏,所以我只需要更新屏幕以响应玩家的操作。 :)
最佳答案
I am creating a UserControl to display/modify the contents of a given inventory slot. However, I'm not sure exactly how to do that. In C++, I would use something like
它默认按照您想要的方式工作。也不需要“ref”关键字。
关于c# - 如何在 C# 中存储对属性的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3267524/