c# - Generic extension method, operators -
i make method "transforms" 1 space another. quite simple thing template in c++ in c# i'm not sure interface/type or how need use "where" clause in order compiler understand want. c++ function looked this:
template<class t> t transform(t s, t s1, t s2, t d1, t d2) { t result = (s - s1) / (s2 - s1) * (d2 - d1) + d1; return result; }
and first stab @ generic c# version (in extension methods), looks this:
public static t transform<t>(t s, t s1, t s2, t d1, t d2) { t result = (s - s1) / (s2 - s1) * (d2 - d1) + d1; return result; }
alas c# me more specific types, i.e.
"error cs0019: operator '-' cannot applied operands of type 't' , 't'".
what c# want me do?
you cannot directly tell compiler via constraint t implements operator. can tell compiler t implements class. if class overloads operator, can use it.
for example, class defines '-' operator
public class stuff { public stuff(int number) { number = number; } public int number { get; set; } public static stuff operator -(stuff a, stuff b) { return new stuff(a.number - b.number); } //define other operators in same way... }
then, in method, can this:
public static t transform<t>(t s, t s1, t s2, t d1, t d2) t : stuff { stuff result = (s - s1) / (s2 - s1) * (d2 - d1) + d1; return (t)result; }
alternatively, can use dynamic, throw exception if operator not exist.
Comments
Post a Comment