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

时间:2010-07-16 17:47:42

标签: c# reference properties

我正在制作游戏,目前我正在为它制作库存系统。我有一个代表玩家的课程,如下所示:

class Player {
    public Weapon WeaponSlot {get;set;}
    public Shield ShieldSlot {get;set;}
    //etc.
}

Weapon,Shield等是通用Item类的子类:

class Item {
    //...
}

class Weapon : Item {
    //...
}

有武器等的子类,但这并不重要。

无论如何,我正在创建一个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");

另外,关于表现,我并不太关心。这不是一个实时游戏,所以我只需更新屏幕以响应玩家的动作。 :)

6 个答案:

答案 0 :(得分:4)

  

我正在创建一个UserControl   显示/修改给定的内容   库存槽。但是,我不确定   到底该怎么做。在C ++中,我   会使用像

这样的东西

默认情况下,它的工作方式正常。 关键字也不需要。

答案 1 :(得分:3)

基本上你要创建的是一个属性浏览器。看看Windows Forms的PropertyGrid控件(阅读文档以了解它是如何工作的和/或使用Reflector来阅读代码)。

简短的回答是简单地使用反射。通过存储PropertyDescriptor,您可以获取并设置给定对象实例的属性成员的值。

答案 2 :(得分:1)

这是afaik的默认行为

答案 3 :(得分:0)

每个class类型对象都是c#中的引用。值类型使用struct声明。

例如:

Weapon w1 = new Weapon();
w2 = w1;//Does not make a copy just makes a second reference to what w1 is pointing to

如果需要输入/输出参数到函数,可以使用ref。如果需要输出参数,可以使用out。如果您只是将引用传递给类型为class的对象,那么您只需传递它并修改类对象本身即可。

答案 4 :(得分:0)

您可以克隆对象以实现您想要的目标:

public class Weapon : ICloneable
{
    public string Name;

    object ICloneable.Clone()
    {
        return this.Clone();
    }
    public Weapon Clone()
    {
        return (Weapon)this.MemberwiseClone();
    }
}

您可以执行以下操作来获取具有所有内部值的该对象的副本:

Weapon w1 = new Weapon();
Weapon w2 = w1.Clone()

答案 5 :(得分:0)

如果您真的想要参考,可以改用字段。它们可以由ref引用。