简体   繁体   English

C#使用params和扩展方法

[英]C# using params and extension methods

Is the params keyword really not supported within extension methods? 扩展方法中是否真的不支持params关键字?

I have found that when I create extension methods with the params keyword, that I get "No overloaded method for X takes 2 arguments". 我发现当我使用params关键字创建扩展方法时,我得到“没有重载的X方法需要2个参数”。 Intellisense recognizes the extension method and even knows that it needs an object array. Intellisense识别扩展方法,甚至知道它需要一个对象数组。

Here's some sample code: 这是一些示例代码:

public static DalRow EasyRetrieveSingle(this DalRow dalRow, object[] parameters) 
{
    Dictionary<string, object> dic = new Dictionary<string, object>();
    for (int i = 0; i < parameters.Length; i += 2)
        dic.Add(parameters[i].ToString(), parameters[i + 1]);

    List<DalRow> list = DalRow.RetrieveByFieldValues(dalRow.Structure, null, dic).Cast<DalRow>().ToList();
    if (list.Count == 0) return null;
    return list[0];
}

Here's some sample code that calls it (to no avail) 这是一些调用它的示例代码(无济于事)

(new X()).EasyRetrieveSingle(1, 2);

看起来你错过了params关键字......

public static DalRow EasyRetrieveSingle(this DalRow dalRow, params object[] parameters) 

You're missing the params keyword in your method declaration. 您在方法声明中缺少params关键字。

public static DalRow EasyRetrieveSingle(
    this DalRow dalRow, params object[] parameters)
                          ↑

This compiles and runs perfectly: 这编译并运行完美:

static class Extensions
{
    public static void Test(this Program program, params object[] args) { }
}

class Program
{
    static void Main()
    {
        new Program().Test(1, 5);
    }
}

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

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