Generics or several classes

Now we have two structures for representing 2d points.

public struct Point2D
{
    public double X { get; set; }
    public double Y { get; set; }
}

public struct Point2DF
{
    public float X { get; set; }
    public float Y { get; set; }
}

Now we need to make a different structure to represent the 2d point for the intergers.

public struct Point2DI
{
    public int X { get; set; }
    public int Y { get; set; }
}

My question is should generics be used here? If I use generics, I will have one single structure instead of three.

public struct Point<T>
{
    public T X { get; set; }
    public T Y { get; set; }
}

But the consumer can set T as a string or some class / struct. What should I do? Is there a way to get T to be double / int / float?

+4
source share
2 answers

, Generics, , , ( , IMO )

, , , , IMO:

public class Point<T>
    where T : struct, IComparable, IFormattable, IConvertible, IComparable<T>, IEquatable<T>
{

    protected readonly Type[] AllowedTypes = 
        {
            typeof(decimal), typeof(double), typeof(short), typeof(int), typeof(long),
            typeof(sbyte), typeof(float), typeof(ushort), typeof(uint), typeof(ulong)
        };

    public Point()
    {   
        if (!this.AllowedTypes.Contains(typeof(T)))
        {
            throw new NotSupportedException(typeof(T).ToString());
        }           
    }

    public T X { get; set; }

    public T Y { get; set; }

    // UPDATE: arithmetic operations require dynamic proxy-Properties or
    // variables since T is not explicitly numeric... :(
    public T CalculateXMinusY()
    {
        dynamic x = this.X;
        dynamic y = this.Y;

        return x - y;
    }
}

. IntelliSense, , . , , , , , .

, , - -, , #, .

+6

, :

public struct Point<T> where T:struct, IComparable

IComparable, struct s


UPDATE

, , Point

public abstract class Point
{
    protected Point()
    {

    }

    public static Point Create<T>(T x, T y)
    {
        if (typeof(T).IsAssignableFrom(typeof(int)))
            return new Point2DI { X = (int)(object)x, Y = (int)(object)y };

        if (typeof(T).IsAssignableFrom(typeof(double)))
            return new Point2D { X = (double)(object)x, Y = (double)(object)y };

        if (typeof(T).IsAssignableFrom(typeof(float)))
            return new Point2DF { X = (float)(object)x, Y = (float)(object)y };

        throw new Exception("Invalid type parameter");
    }
}

public class Point2D : Point
{
    public double X { get; set; }
    public double Y { get; set; }
}

public class Point2DF : Point
{
    public float X { get; set; }
    public float Y { get; set; }
}

public class Point2DI : Point
{
    public int X { get; set; }
    public int Y { get; set; }
}
+3

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


All Articles