简体   繁体   中英

C# create operator overload for concrete type of generic class or struct

My type CRange<T> is defined as

public readonly struct CRange<T>
  where T : struct, IComparable
{
  ...

  public T LowerValue { get; }
  public T UpperValue { get; }
}

Unfortunately, there is no where T: Number .

I mainly use CRange<int> and CRange<double> , and there are a couple of situations where I want to multiply a CRange<> with a factor (= double ).

I tried

public static CRange<double> operator * (CRange<double> i_range, double i_factor)

but this is not allowed, because each operator must contain at least one operand of the type.

Is there any other way to create such an operator?

You can write an extension method -- this is what the runtime does for eg Vector128<T> . This does mean you need a method rather than an operator however.

public static class CRangeExtensions
{
    public static CRange<double> Multiply(this CRange<double> range, double factor)
    {
        return new CRange(range.LowerBound * factor, range.UpperBound * factor);
    }

    // Same for int...
}

If you're OK using preview features, you can make use of Generic math which defines the INumber<T> interface:

public readonly struct CRange<T> where T : INumber<T>
{
    public T LowerValue { get; }
    public T UpperValue { get; }
    
    public CRange(T lower, T upper) => (LowerValue, UpperValue) = (lower, upper);
  
    public static CRange<T> operator * (CRange<T> range, T factor)
    {
        return new CRange<T>(range.LowerValue * factor, range.UpperValue * factor);
    }
}

SharpLab .

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