在C#运算符重载 [英] Operator overloading in C#

查看:138
本文介绍了在C#运算符重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是有点糊涂了与运营商的C#语言超载,可以请你告诉我,是操作符重载在本质上是静态还是动态的。

I was a bit confused with Operator overloading in C# language, Can you Please tell me is Operator overloading static or dynamic in nature.

推荐答案

如果你的意思是它是多态还是不呢?那么答案是否定的 - 运算符是由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
    }
}



第一次调用 == 用于字符串声明的运营商,因为编译器知道这两个操作数的类型字符串。这两个字符序列进行比较,发现它们相等,并返回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.

第二次调用 == 使用中声明的运算符对象因为编译时类型的表达式 OY 对象。这个操作符只比较引用。引用不同(它们指的是不同的值),因此该返回False。请注意,在这种情况下,的的 OY 将把在执行字符串时间,但是的的考虑当编译器决定哪些超载打电话。 (它的只有的知道 OY 的为类型的对象

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.)

第三个呼叫 == 使用动态类型来发现操作者在执行时,使用的实际的类型的引用,而不是在编译时间类型的表达式。此发现过载的字符串等再次运算符返回true。

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.

这篇关于在C#运算符重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆