简体   繁体   中英

Floating point comparison on generic property

i have a generic class with some properties:

class MyClass<TValueType>
    where TValueType : struct, IComparable
{        
    public TValueType Target
    {
        get { return _target; }
        set
        {
            if (Equals(_target, value)) return;
            _target = value;
            RaiseTargetChanged(value);
        }
    }

    // Other stuff ...
}

As you see i compare with object.Equals to avoid excessive event invokes. However, i have an extension method for floating point comparison i would like to use if TValueType is double, float or decimal:

public static bool AlmostEqual(this double x, double y, double delta = 0.00001d)
public static bool AlmostEqual(this float x, float y, float delta = 0.00001f)
public static bool AlmostEqual(this decimal x, decimal y, decimal delta = 0.00001m)

Do should i type compare and cast TValueType and make the proper floating point comparison, or is there a smarter way?

EDIT: Solution by David Heffernan:

I've made it mandatory to pass a comparer to the class:

class MyClass<TValueType>
{
    public MyClass(IComparer<TValueType> comparer) { ... }
}

and then i pass a custom comparer:

public class FloatingPointComparer : IComparer<double>, IComparer<float>, IComparer<decimal>, IComparer
{
    public int Compare(double x, double y)
    {
        return FloatingComparisonExtensions.CompareTo(x, y);
    }
    // Rest of Compares are the same
} 

I'm using a IComparer instead of an IEqualityComparer since i need to verify Target against a Maximum and Minimum value.

Rather than having type checking code in your generic class, which feels somewhat dirty, you could ask the consumer to supply an IEqualityComparer<TValueType> interface to perform the comparison. If the consumer does not provide one then the code would default to Object.Equals .

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