Work with generic and double

I need to calculate in the general class. I found several solutions, such as here: Solution for overloaded operator restriction in .NET generics , but I need to hide T with double. Is it possible to distinguish T twice? Therefore, I can write the code as follows:

class Myclass<T>{
  T value;
  public double Half() {
    return  i.value  / 2;
  }
}

Myclass<int> i = new Myclass<int>();
double x = i.Half();

Thank!

+3
source share
3 answers

Genetics and operators do not mix. In 4.0 you can use dynamicfor this; Until then, MiscUtil has DivideInt32, which should work perfectly for cases such as:

T half = Operator.DivideInt32(value, 2);

double . double ( T) . ToString Parse, , .

- Convert, :

return Operator.Convert<T,double>(value) / 2;
+2

, , : #.

, , Half :

public double Half() {
    if (typeof(T) == typeof(double))
        return HalfDouble();
    else if (typeof(T) == typeof(int))
        return HalfInt();
    else if (typeof(T) == typeof(decimal))
        return HalfDecimal();
    // etc.
}
+1

, Func<T,double>, T double. double Half() 2.

" #" .

0

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


All Articles