Operator overloading in the general structure: can I create overloads for certain types of (?) General?

I define physical units in C # using common structures, and everything goes well until an error occurs:

One of the parameters of the binary operator must be a containing type

when trying to overload math operators so that they convert between different units. So, I have something like this:

public interface ScalarUnit { } public class Duration : ScalarUnit { } public struct Scalar<T> where T : ScalarUnit { public readonly double Value; public Scalar(double Value) { this.Value = Value; } public static implicit operator double(Scalar<T> Value) { return Value.Value; } } public interface VectorUnit { } public class Displacement : VectorUnit { } public class Velocity : VectorUnit { } public struct Vector<T> where T : VectorUnit { #... public static Vector<Velocity> operator /(Vector<Displacement> v1, Scalar<Duration> v2) { return new Vector<Velocity>(v1.Magnitude / v2, v1.Direction); } } 

There are no errors for the + and - operators, where I just work on Vector<T> , but when I replace the block with T , he suddenly doesnโ€™t like it, Is there a way to make this work?

I decided that this would work, since Displacement implements the VectorUnit interface, and in the structure header where T : VectorUnit . Am I at least on the right track here? I am new to C #, so itโ€™s hard for me to understand what happens sometimes.

+4
source share
1 answer

I do not think that operators can be shared.

I could think of hard type coding in a statement, i.e. if typeof (T). GetGenericParameters () [0] - this or that type of blah blah.

Another approach that I would prefer is to implement a common interface / base class in all subclasses that return a double, and then from the operator you drop it to that interface / b. class and get the values โ€‹โ€‹to calculate.

Note: convention , interface names should always begin with I (example: IScalarUnit ).

+2
source

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


All Articles