mercredi 29 octobre 2014

C# how to overload an operator of a generic class with operands of different generic types of the generic class


Vote count:

0




There have been a lot of similar questions asked but all involve operands of same type or same generic type. This one in particular (How can I use a generic type parameter with an operator overload?) is close to what I am looking for but no answer or work-around.


Is it possible to do something like this for the ‘*’ operator overload:



public class MyNumericClass<T>
{
public double Value { get; set; }

//OK but works only for same type operands
public static double operator *(MyNumericClass<T> left, MyNumericClass<T> right)
{
return left.Value * right.Value;
}

//****Pseudo Code for different type operands - not OK****
public static double operator *<TRight>(MyNumericClass<T> left, MyNumericClass<TRight> right)
{
return left.Value * right.Value;
}

static void Test()
{
MyNumericClass<int> i = new MyNumericClass<int>();
MyNumericClass<int> j = new MyNumericClass<int>();
MyNumericClass<string> s = new MyNumericClass<string>();
double r1 = i * j;
double r2 = i * s; //Operator '*' cannot be applied to operands...
}
}


I need to have a specific overload for different generic types. A non-generic superclass will not do in this case as I have other overloads of the operator (not shown here) and ambiguous calls will be produced if I use a parameter of superclass type and not the exact generic type.


Is it possible to do this or is there a work-around? Is it possible to use op_Multiply instead? (Tried it but couldn’t make it work).


P.S. I don’t see any reason why something like this should not be possible.



asked 44 secs ago

GDS

21






C# how to overload an operator of a generic class with operands of different generic types of the generic class

Aucun commentaire:

Enregistrer un commentaire