Operators in C # Generics

In C ++, we can write the following:

template <typename T>

    void Print(T a, T b) 
      {
          cout<<a+b<<endl;
      }

Print(12,56) or Print('c','s');

If we overload operators for user-defined types (classes), we can also write:

Person a, b; Print(a,b);

but in C # we cannot write operators such as + - or * / why can't we write this? and how can we do this (use operators in common methods)?

+4
source share
3 answers

how can we do this (use operators in common methods)

As a rule, we cannot. For most operators, if used with a type parameter (for example, T), the compiler cannot work out the applicable overload for use at compile time.

( , ), , . , System.Uri - , ==. , :

class Test<T> where T : Uri
{
  internal void Method(T x, T y)
  {
    bool ok = x == y;
  }
}

. , .

, T - (struct), == () * () << ( ) . #.

dynamic , , , .

+2

, , MiscUtils. . , .

, , operator+, Operator.Add. operator+, , . , .

# ( CLR). - ++ .

+1

?

langauge.

( )?

.

#.

- ( ), . .

0
source

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


All Articles