简体   繁体   English

用params重载的C#方法

[英]C# method overloading with params

Please Help! 请帮忙!

What am I doing wrong? 我究竟做错了什么?

    static void f1(Color color, params float[] f)
    {
        System.Console.WriteLine("Here is f1 for float");
    }

    static void f1(Color color, params int[] f)
    {
        System.Console.WriteLine("Here is f1 for int");
    }

    static void Main()
    {
        f1(null,0);
    }

I can't invoke f1(null,0); 我无法调用f1(null,0); I get compile time error. 我得到编译时错误。

How this staff can be overcome assuming I indeed need those method signatures? 假设我确实需要这些方法签名,如何克服这些工作人员?

EDIT: As for Compile-tme error - ReSharper complains: 编辑:至于编译错误 - ReSharper抱怨:

Cannot resolve method f1(null,int), candidates are: 无法解析方法f1(null,int),候选者是:

void f1(Syste.Drawing.Color, params[] float) void f1(Syste.Drawing.Color,params [] float)

void f1(Syste.Drawing.Color, params[] int) void f1(Syste.Drawing.Color,params [] int)

I think the problem is you are passing null for Color which might be upsetting the function, either change that to Color? 我认为问题是你正在为Color传递null,这可能会扰乱函数,要么将其更改为Color? (since it is a struct) or pass a valid Color value (因为它是结构)或传递有效的颜色值

static void f1(Color? color, params float[] f)

static void f1(Color? color, params int[] f)

You cannot pass null in place of a struct parameter, that is Color in your example. 您不能传递null来代替struct参数,即示例中的Color。 The problem is not about the params parameters. 问题不在于params参数。 Some valid calls would be like; 一些有效的电话会是这样的;

f1(Color.Black, 0); // prints "Here is f1 for int"
f1(Color.Black, 0f); //prints "Here is f1 for float"
f1(Color.Black, 0, 5, 6, 7); // prints "Here is f1 for int"
f1(Color.Black, 0, 5.4f, 6, 7); //prints "Here is f1 for float"

If Color is System.Drawing.Color then parameter color can't be null. 如果Color是System.Drawing.Color则参数color不能为null。 If you want color to be nullable use Color? 如果你想要color可以使用Color? type 类型

f1(Color.Black, 0) // works
f1(null, 0) // Doesn't work

您需要在Color参数中传递System.Drawing.Color Object not null。

First of all, you cant use null for the Color parameter. 首先,你不能使用null作为Color参数。 To use one of both codes use this for ints: 要使用其中一个代码,请使用以下代码:

f1(SystemColors.ActiveBorder, new int[]{0});

or this for floats: 或者这个浮动:

f1(SystemColors.ActiveBorder, new float[]{0});

the way you use it it will always call the int version. 你使用它的方式总是调用int版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM