重载运算符

发布日期:2026-07-14 02:12:04   来源 : 杭州电子商务研究院    浏览量 :12
杭州电子商务研究院 发布日期:2026-07-14 02:12:04  
12

介绍

C# 和许多其他编程语言中有一个概念称为重载。这是一种实现多态性(面向对象编程范式)的技术。根据定义,多态性意味着您可以拥有多个可互换的类,这些类以不同的方式实现方法和属性。此概念也适用于函数。您可以以不同的形式定义它们,这些形式会根据应用程序需要处理的不同情况进行调整。一个常见的例子是具有相同名称但不同参数列表的方法。

关于超载,您需要了解的一些重要事项:

  1. 重载方法在传递的参数的数量和类型上有所不同。
  2. 您只能有一个具有相同名称、顺序和参数类型的方法。尝试使用多个方法将导致编译器错误。
  3. 编译器不考虑重载方法的返回类型,但它禁止您声明两个具有相同签名和不同返回类型的方法。

我们将从方法重载开始,然后将目光转向运算符重载。

方法重载

为什么我们需要在 C# 中进行重载?我们可能需要一个类,它对传递给其方法的不同数量的参数做出略有不同的反应,但我们不希望在每种情况下为该方法使用不同的名称。

重载方法有三种不同的方式:

  1. 参数数量
  2. 参数的数据类型
  3. 方法参数的顺序

我们用一个示例类来演示一下。

      using System;

namespace Overloader
{
    class Mathher
    {

    public int Multiply(int a, int b)
        {
            return (a * b);
        }
        public string Multiply(int a, string b)
        {
            string result="";
            for (int i = 0; i < a; i++)
            {
                result = result + b;
            }
            return result;
        }
        public string Multiply(string a, int b)
        {
            string result = "";
            for (int i = 0; i < b; i++)
            {
                result = result + a;
            }
            return result;
        }
        static void Main(string[] args)
        {
            Mathher m = new Mathher();
            int a = 10;
            int b = 20;
            Console.WriteLine($"Calling the Multiply function with two integers -> int({nameof(a)}):{a}, and int({b}):{b}");
            Console.WriteLine($"Result: {m.Multiply(a, b)}");
            int c = 15;
            string d = "P";
            Console.WriteLine($"Calling the Multiply function with one integer and one string -> int({nameof(c)}):{c}, and str({d}):{d}");
            Console.WriteLine($"Result: {m.Multiply(c, d)}");
            int e = 9;
            string f = "K";
            Console.WriteLine($"Calling the Multiply function with one string and one integer -> str({nameof(e)}):{e}, and int({f}):{f}");
            Console.WriteLine($"Result: {m.Multiply(e, f)}");
            Console.ReadKey(); ;
        }
    }
}
    

在这个类中,我演示了重载类方法的三种不同方法。第一个签名从两个输入整数返回一个整数,它是它们相乘的乘积。第二个签名接受一个整数和一个字符串,并重复字符串整数次。第三个签名是完成循环所必需的,这意味着我们可以使用字符串和整数作为参数来调用该方法,它还会生成字符串整数次。

      Calling the Multiply function with two integers -> int(a):10, and int(20):20
Result: 200
Calling the Multiply function with one integer and one string -> int(c):15, and str(P):P
Result: PPPPPPPPPPPPPPP
Calling the Multiply function with one string and one integer -> str(e):9, and int(K):K
Result: KKKKKKKKK
    

运算符重载

C# 提供了内置类型支持的运算符。运算符有很多种类型,最常见的可能是算术运算符,您已经很熟悉了。运算符具有优先级,它定义了它们的求值顺序,而且它们也有严格的规则。如果您有兴趣了解有关顺序的重要性的更多信息,请阅读我的相应指南。开发人员通常将运算符添加到其自定义类型或类中的原因是为了与已经与内置类型一起使用的运算符兼容。另一个原因是您可能希望提供与这些内置运算符类似的功能。这是关于您可以重载的运算符的非常详细的介绍。

请想象一下,如果您愿意的话,您想要创建一个小型数学应用程序,来计算二维空间中两个三角形的总表面。

您可以使用以下定义构造您的类,以使用实例方法添加两个三角形。

      Triangle tri1 = new Triangle(2,3,4);
Triangle tri1 = new Triangle(10,15,20);

Triangle result = tri1.Add(tri2);
    

您也可以使用静态方法实现解决方案。

      Triangle tri1 = new Triangle(2,3,4);
Triangle tri1 = new Triangle(10,15,20);

Triangle result = Triangle.Add(tri1,tri2);
    

让我们使它看起来更专业,并尝试重载我们的操作员以利用 C# 功能的强大功能。

      Triangle tri1 = new Triangle(2,3,4);
Triangle tri1 = new Triangle(10,15,20);

Triangle result = tri1 + tri2;
    

让我们创建一个支持上述内容的类。我们需要两个具有不同签名的构造函数,并且需要重写+运算符来实现这一点。有一个简单的公式可以帮助您计算三角形的表面积:T = (a * ma) / 2。这是一条边的长度乘以该边与另外两条边的交点之间的最短距离,然后除以 2。

      using System;

namespace Overloader
{
    public class Triangle
    {
        public int a;
        public int ma;
        public double surface;
        public Triangle(int a, int ma)
        {
            this.a = a;
            this.ma = ma;
            this.surface = (a * ma) / 2;
        }
        public Triangle(double surface)
        { this.surface = surface; }
        public static Triangle operator +(Triangle tri1, Triangle tri2)
        {
            Triangle result = new Triangle((tri1.surface + tri2.surface));
            return result;
        }
    }
    
    class Mainer
    {
        static void Main(string[] args)
        {
            Triangle tri1 = new Triangle(8, 12);
            Console.WriteLine($"The first triangle: {nameof(tri1)} with surface is:{tri1.surface}");
            Triangle tri2 = new Triangle(14, 16);
            Console.WriteLine($"The second triangle: {nameof(tri2)} with surface is:{tri2.surface}");
            Triangle tri3 = tri1 + tri2;
            Console.WriteLine($"The third triangle: {nameof(tri3)} with surface is:{tri3.surface} is the product of {nameof(tri1)} and {nameof(tri2)}");
            Console.ReadKey(); ;
        }
    }
}
    

在我们的运算符重写中,我们只是返回一个新实例,该实例是使用只接受一个参数(即表面)的构造函数创建的。

调用该类将产生以下结果。

      The first triangle: tri1 with surface is:48
The second triangle: tri2 with surface is:112
The third triangle: tri3 with surface is:160 is the product of tri1 and tri2
    

nameof运算仅用于动态打印变量的名称。它接受一个对象并返回一个带有其名称的字符串。

结论

重载有两个不同的类别。一个是类方法,另一个是运算符。这两个概念都非常简单,易于掌握,并为您的应用程序带来新功能。在本指南中,我们学习了如何重载方法并使用独特功能扩展我们的类,然后我们重新审视了这个想法并重载了一个内置运算符,该运算符允许我们计算两个三角形表面的总和。我希望这对您有所帮助,并且您找到了您想要的东西。感谢您的阅读。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据