开发者

Operator overloading in generic struct: can I create overloads for specific kinds(?) of generic?

I'm defining physical units in C#, using generic structs, and it was going okay until I got the error:

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

when trying to overload the mathematical 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 aren't any errors for the + and - operators, where I'm just working on a Vector<T>, but when I substitute a unit for T, suddenly it doesn't like it. Is there a way to make this work?

I figured it would work, since Displacement implements the VectorUnit interface, and I have where T : VectorUnit in the struct header. Am I at least on the right track here? I'm new to C# so I have difficulty understanding what's going on sometimes.


I don't think operators can be generic.

I would maybe consider hardcoding the types in the operator, i.e. if typeof(T).GetGenericParameters()[0] is this or that type blah blah.

Another approach whouch I would even prefer is implementing a common interface/base class in all the subclasses that returns a double, then, from the operator, you cast it down to that interface/b. class and get the values to calculate.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜