How to save property reference in C #?

I am creating a game and am currently working on an Inventory system for it. I have a class to represent a player that looks like this:

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

Weapons, Shield, etc. are subclasses of the general class Item:

class Item {
    //...
}

class Weapon : Item {
    //...
}

There are subclasses of weapons, etc., but that doesn't matter.

In any case, I create a UserControl to display / modify the contents of this inventory slot. However, I do not know exactly how to do this. In C ++, I would use something like:

new InventorySlot(&(player.WeaponSlot));

But I can not do this in C #.

I found the TypedReference structure, but this does not work, since you are not allowed to create a field with one of these structures, so I could not store it for use later in the control.

Is reflection the only way, or is there another means that I don't know about?

EDIT ----

, :

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");

, , . , .:)

+3
6

, .

+3

UserControl / . . ++ -

. "ref" .

+4

afaik

+1

class ​​#. 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, .

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()
0

, . ref.

0

Source: https://habr.com/ru/post/1755028/


All Articles