Where is op_addition in [int, float, double]

Dummy:

public object Addition(object a, object b) { var type = a.GetType(); var op = type.GetMethod("op_Addition", BindingFlags.Static | BindingFlags.Public); return op.Invoke(null, new object[] { a, b }); } 

This method complains about int / float / double, which cannot find these methods (op_Addition).

So how to create a generic add method?

+6
source share
1 answer

Yes, they are not ordinary operators that exist as such elements - instead, there are built-in IL statements.

(The same is almost true for string concatenation, except that the C # compiler builds a call to string.Concat .)

If you are using C # 4 and .NET 4, the easiest way is to use dynamic typing:

 public dynamic Addition(dynamic x, dynamic y) { return x + y; } 

For earlier versions, you will need special types of certain types: (

It's not clear what your context is, but you can find Marc Gravell 's article on generic operators .

+8
source

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


All Articles