使用 params 关键字的方法重载 [英] Method overloading using params keyword

查看:47
本文介绍了使用 params 关键字的方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class D
{
    public void foo(int z, int x)
    {
        Console.WriteLine("foo with two parameters");
    }
    public void foo(params int[] z)
    {
        Console.WriteLine("foo with two params parameter");
    }
}
class Program
{
    public static void Main()
    {       
        D obj = new D();
        obj.foo(10,20);
    }
}

当我运行这段代码时,执行方法 foo(int x, int y) 而不是 foo(params int[] z).这是为什么?

When I run this code, the method foo(int x, int y) is executed instead of foo(params int[] z). Why is this?

推荐答案

C# 编译器将始终尝试选择与参数最匹配的方法.在您的情况下, foo(int, int) 重载与您的输入参数完全匹配,而 foo(params int) 重载是较弱的匹配.

The C# compiler will always try to select the metod that matches the arguments most closely. In your case the foo(int, int) overload matches your input arguments exactly, while the foo(params int) overload is a weaker match.

如果您有兴趣,这里是 C# 中方法重载的一个很好的概述:http://csharpindepth.com/Articles/General/Overloading.aspx

Here is a nice overview of method overloading in C# if you are interested: http://csharpindepth.com/Articles/General/Overloading.aspx

这篇关于使用 params 关键字的方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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