简体   繁体   English

C#中的运算符重载

[英]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. 答案是否定的 - 除非你使用dynamic类型,否则C#编译器会静态找到运算符。 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 . 第一次调用==使用在string声明的运算符,因为编译器知道两个操作数都是string类型。 It compares the two character sequences, finds they're equal, and returns True. 它比较两个字符序列,发现它们相等,并返回True。

The second call to == uses the operator declared in object because the compile-time types of the expressions ox and oy are object . 第二次调用==使用在object声明的运算符,因为表达式oxoy的编译时类型是object This operator only compares references. 此运算符仅比较引用。 The references are different (they refer to different values), so this returns False. 引用是不同的(它们引用不同的值),因此返回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. 请注意,在这种情况下, oxoy将在执行时引用字符串,但在编译器决定调用哪个重载时不会考虑这一点。 (It only knows of ox and oy as being of type object .) (它知道的oxoy为类型的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. 这会发现string的重载,因此操作符再次返回True。

The basic Operator Overloading is static: 基本的运算符重载是静态的:

public static SomeClass operator ++(SomeClass arg)

Try this Series showing some examples 试试这个系列展示一些例子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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