vendredi 6 décembre 2019

Summing the values of two same-type structs

So I have a struct like this:

public struct Attributes {
    public int vitality;
    public int intelligence;
    public int dexterity;
    public int agility;
}

And I use it like this:

Attributes a = new Attributes();
Attributes b = new Attributes();

And what I want to achieve is this:

Attributes c = new Attributes();
c = a + b;

I want this to give me the sum of these 4 variables I specified above of those two Attributess.

Inside the struct, I tried to have this:

public static Attributes operator +(Attributes x, Attributes y) {
        PropertyInfo[] info = typeof(Attributes).GetType().GetProperties();
        for (int i = 0; i < info.Length; i++) {                
            info[i].SetValue(x, (int) info[i].GetValue(x) + (int) info[i].GetValue(y), null);
        }

        return x;
}

This apparently doesn't work, giving me an error.

Can you guys help me about this? What could I do to achieve what I want? Thanks.





Aucun commentaire:

Enregistrer un commentaire