How to do math operations with a struct? [duplicate]

3

I have the following structure:

public struct vetor
{
    public float X, Y;
    public vetor(float X, float Y)
    {
        this.X = X;
        this.Y = Y;
    }
}

And this code:

Vars.vetor _visao;
Vars.vetor _recoil; //Os 2 possuem valores, eu tirei para ilustrar melhor

Vars.vetor towrite = _visao - _recoil * 2.0f;

But it is returning the following error:

  

Error CS0019 The "*" operator can not be applied to operands of types   "Vars.vetor" and "float"

I would like to know if you would like to make this code work as follows:

towrite.X = _visao.X - _recoil.X * 2.0f;
towrite.Y = _visao.Y - _recoil.Y * 2.0f;

I thought this was impossible until I saw that the class Vector2 supports this kind of thing. That is, how does she do it?

    
asked by anonymous 20.08.2017 / 00:45

1 answer

4

This is done with operators methods .

using static System.Console;

public class Program {
    public static void Main() {
        var vetor = new Vetor(3, 4);
        var vetor2 = vetor * 2f;
        WriteLine($"X = {vetor2.X}, Y = {vetor2.Y}");
    }
}

public struct Vetor {
    public float X, Y;
    public Vetor(float X, float Y) {
        this.X = X;
        this.Y = Y;
    }
    public static Vetor operator *(Vetor left, float right) {
        return new Vetor(left.X * right, left.Y * right);
    }
}

See working on .NET Fiddle . And No Coding Ground . Also put it on GitHub for future reference .

Obviously you need to do the other operators, but the technique is this.

Has the source of all .NET classes .

    
20.08.2017 / 01:04