C#中的重载

35 篇文章 0 订阅

重载就是一个类里面有多个同名的方法,访问修饰符相同,返回值相同,方法名相同,但参数列表不同。

那重载的方法怎么区分呢,对了,重载的方法根据参数的个数,或者参数的类型不同来区分

值得注意的是,仅仅方法的返回值不同不能叫重载,编译报错。
还有,尽管ref和out在运行时的处理方式不同,但是在编译时的处理方式却相同,因此,如果一个方法采用out参数,另一个方法采用ref参数,则无法重载这两个方法,会编译报错

下面来一个例子看看重载的使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
    class Math
    {
        //第一个方法有两个参数,求AB的和
        public static void Add(int a,int b)
        {

            Console.WriteLine(a+b);
        }

        //第二个方法有三个参数,求ABC的和
        public static void Add(int a, int b,int c)
        {

            Console.WriteLine(a + b + c);
        }
    }
}

在main方法中重载Add方法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            //调用两个参数的Add方法
            Math.Add(1,5);

            //调用三个参数的Add方法,重载了Add方法
            Math.Add(1, 5, 7);

        }


    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#,可以通过重载运算符来实现矩阵的乘法运算符重载。通过重载乘法运算符,我们可以实现两个矩阵对象之间的乘法操作。重载乘法运算符的方法是在类定义一个名为"operator*"的方法。该方法接受两个矩阵对象作为参数,并返回一个新的矩阵对象,表示两个矩阵的乘法结果。 下面是一个示例代码,展示了如何在C#重载矩阵乘法运算符: ```csharp public class Matrix { // 矩阵的行数和列数 private int rows; private int columns; // 矩阵的数据 private int[,] data; // 构造函数 public Matrix(int rows, int columns) { this.rows = rows; this.columns = columns; this.data = new int * matrix2.data[k, j]; } result.data[i, j = sum; } } return result; } } // 示例用法 Matrix matrix1 = new Matrix(2, 3); Matrix matrix2 = new Matrix(3, 2); Matrix result = matrix1 * matrix2; ``` 在上面的示例,我们定义了一个名为Matrix的类,其包含了重载乘法运算符的方法。在使用时,我们可以创建两个矩阵对象matrix1和matrix2,并通过乘法运算符*将它们相乘得到结果矩阵result。 请注意,为了进行矩阵乘法运算,我们需要确保第一个矩阵的列数与第二个矩阵的行数相等。如果不满足这个条件,就无法进行矩阵乘法运算。 以上是关于C#矩阵乘法运算符重载的解释和示例代码。希望对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [C#运算符重载](https://blog.csdn.net/q269399361/article/details/52924869)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* *3* [C#运算符重载](https://blog.csdn.net/cloproad/article/details/79028076)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值