What version of .NET are you using? If you are using .NET 3.5, then I have a generic operators implementation in MiscUtil (free etc).
This has methods like T Add<T>(T x, T y)
, and other variants for arithmetic on different types (like DateTime + TimeSpan
).
Additionally, this works for all the inbuilt, lifted and bespoke operators, and caches the delegate for performance.
Some additional background on why this is tricky is here.
You may also want to know that dynamic
(4.0) sort-of solves this issue indirectly too - i.e.
dynamic x = ..., y = ...
dynamic result = x + y; // does what you expect
Re the comment about <
/ >
- you don't actually need operators for this; you just need:
T x = ..., T y = ...
int c = Comparer<T>.Default.Compare(x,y);
if(c < 0) {
// x < y
} else if (c > 0) {
// x > y
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…