简体   繁体   中英

Operator overloading in C#

我对C#语言中的运算符重载感到有点困惑,你能不能告诉我运算符是静态还是动态的。

If you mean "is it polymorphic or not?" then the answer is no - operators are found statically by the C# compiler, unless you're using the dynamic type. For example, consider this code:

using System;

class Test
{    
    static void Main(string[] args)
    {
        string x = "hello";
        string y = new string(x.ToCharArray());        
        Console.WriteLine(x == y); // True

        object ox = x;
        object oy = y;
        Console.WriteLine(ox == oy); // False

        dynamic dx = x;
        dynamic dy = y;
        Console.WriteLine(dx == dy); // True
    }
}

The first call to == uses the operator declared in string , as the compiler knows that both operands are of type string . It compares the two character sequences, finds they're equal, and returns True.

The second call to == uses the operator declared in object because the compile-time types of the expressions ox and oy are object . This operator only compares references. The references are different (they refer to different values), so this returns False. Note that in this case the values of ox and oy will refer to strings at execution time, but that isn't taken into account when the compiler decides which overload to call. (It only knows of ox and oy as being of type object .)

The third call to == uses dynamic typing to discover the operator at execution time, using the actual types of the references, rather than the compile-time types of the expressions. This discovers the overload in string , and so again the operator returns True.

The basic Operator Overloading is static:

public static SomeClass operator ++(SomeClass arg)

Try this Series showing some examples

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM