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.
source share