开发者

Are there any interfaces shared by value types representing numbers?

开发者 https://www.devze.com 2023-01-28 20:07 出处:网络
I would like to be able to create various structures with variable precision. For example: public struct Point<T> where T : INumber

I would like to be able to create various structures with variable precision. For example:

public struct Point<T> where T : INumber
{
    public T X;
    public T Y;

    public static Point<T> operator +(Point<T> p1, Point<开发者_JS百科T> p2)
    {
        return new Point<T>
                   {
                       X = p1.X+p2.X,
                       Y = p1.Y+p2.Y
                   };
    }
}

I know Microsoft deals with this by creating two structures - Point (for integers) and PointF (for floating point numbers,) but if you needed a byte-based point, or double-precision, then you'll be required to copy a lot of old code over and just change the value types.


There's a simple reason why you cannot do that: Operators are non-virtual, i.e., the compiler must know at compile time whether p1.X+p2.X is an integer addition or a double addition.


No, there is no such interface.

0

精彩评论

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