简体   繁体   中英

Is using one generic method or multiple overloaded methods more appropriate?

I am working on a project where I will be working with many types of mathematical values, such as fractions, decimal numbers, and mathematical constants (ie, pi, Euler's number).

I have created an abstract base class, from which each of those types will inherit, with this code.

public abstract class MathValue
{
    public abstract double Value { get; set; }

    protected bool irrational;

    public virtual bool IsIrrational
    {
        get { return this.irrational; }
    }

    public virtual T ToValueType<T>(bool ignoreConstraints) where T : MathValue;

    public abstract MathValue Add<TParam>(TParam val) where TParam : MathValue;
    public abstract MathValue Subtract<TParam>(TParam val) where TParam : MathValue;
    public abstract MathValue Multiply<TParam>(TParam val) where TParam : MathValue;
    public abstract MathValue Divide<TParam>(TParam val) where TParam : MathValue;
}

However I am now questioning whether it is appropriate to use generic methods here, or if I should replace those methods with overloaded methods in each of the derived classes.

Which would be more appropriate in this case?

I generally feel that overloads are best for scenarios where you need to customize functionality based on a type, but generics are good for functionality that is not type dependent and shared across types.

A good example of an overload class that does different things based on input parameters is the static Convert class methods, such as ToInt32 which has something like 32 overloads.

A good example of a generic class that does the same thing for any type is List<T> which will let you put any type in a List in a strongly-typed way, acting the same way for any type T.

An example of returning ToString() values:

If I want to output the ToString() DIFFERENTLY for each type, I'd use different overloads (or even different classes) for the different parameter types:

public class MyMathClass
{
    public string GetToString(int myValue)
    {
        return "My Int: " + myValue;
    }

    public string GetToString(double myValue)
    {
        return "My Double: " + myValue;
    }
}

If I want to output ToString for ANY object, I might not use generics since any object has a ToString() method... However for the sake of my example I will:

public class MyMathClass<T>
{
    public void GetToString<T>(T myValue)
    {
        return myValue.ToString();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM