c# - 如何在 C# 中存储对属性的引用?

标签 c# reference properties

我正在创建一个游戏,目前正在为它开发库存系统。我有一个代表玩家的类,它看起来像这样:

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/

相关文章:

c# - 具有舒适的 IDE 和 GUI 设计器 (Windows/Linux/OS X) 和信息可视化库的跨平台 GUI?

c++ - std::iterator::reference 必须是引用吗?

ios - 当 Swift 中的变量值发生变化时执行方法

python - 如何检查一个变量是否是一个属性

c# - Application.Current <- 它是如何工作的?

c# - 在 C# 中,如何使用反射访问花括号构造函数?

c# - 想不出解决这个多对多的查询

javascript - Uncaught ReferenceError : "changing" is not defined (JavaScript)

C++:对 map 的引用

java - 在复杂环境中处理属性和 log4j 的工具