或(|),异或(^),与(&安培)超载 [英] OR(|), XOR(^), AND(&) overloading

查看:186
本文介绍了或(|),异或(^),与(&安培)超载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何重载和放大器;,|和^运营商在C#和如何超载工作?

How do I overload the &, | and ^ operators in C# and how does overloading work?

我一直在试图找到一些很好的答案了一段时间,但没有发现任何。我将分享任何有用的文章。

I have been trying to find some good answers for some time but have not found any. I will share any helpful articles.

推荐答案

通过实施运营商为你的类在C#中,你是不是真正的重载的运营商。你只是实施他们的第一次。他们的方法,就像任何其他的,但有特殊的语法。与其说 C =添加(A,B)你叫 C = A + B ,其中<$ C $的C> + 是一个操作符(方法)返回一个值。

By implementing operators for your classes in C#, you are not actually overloading operators. You are simply implementing them for the first time. They are methods, just like any other, but with special syntax. Instead of calling c = Add(a, b) you call c = a + b, where + is an operator (method) that returns a value.

通过实施以下方法,在&安培; = | = ^ = 方法已经自动实现。

By implementing the following methods, the &= |=, and ^= methods have been automatically implemented.

public class MyClass
{
    public static MyClass operator &(MyClass left, MyClass right)
    {
        return new MyClass();
    }

    public static MyClass operator |(MyClass left, MyClass right)
    {
        return new MyClass();
    }

    public static MyClass operator ^(MyClass left, MyClass right)
    {
        return new MyClass();
    }
}

var a = new MyClass();
var b = new MyClass();

var c = a & b;
var d = a | b;
var e = a ^ b;

a &= b; // a = a & b;
c |= d; // c = c & d;
e ^= e; // e = e ^ e;

重载的是在编译时进行。它保证了基于该方法的名称和参数类型和数量的特定方法被调用。

Overloading is performed at compile time. It ensures that a specific method is called based on the method's name and parameter type and count.

Overiding 的在运行时进行。它允许被调用而不是父方法的子类的方法中,即使该实例是被视为父类

Overiding is performed at runtime. It allows a subclass's method to be called instead of the parent method, even when the instance was being treated as the parent class.

这篇关于或(|),异或(^),与(&安培)超载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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