字符串数组和参数的扩展方法

时间:2012-11-27 22:12:55

标签: c# extension-methods params

如何同时编译这两种方法?

public static IEnumerable<string> DoSomething(params string[] args)
{ // do something }
public static IEnumerable<string> DoSomething(this string[] args)
{ // do something }

我收到了这个编译错误:

Type 'Extensions' already defines a member called 'DoSomething' with the same parameter types Extensions.cs

所以我可以这样做:

new string[] { "", "" }.DoSomething();
Extensions.DoSomething("", ""); 

如果没有params方法,我必须这样做:

Extensions.DoSomething(new string[] { "", "" });

更新:根据O. R. Mapper

的答案
public static IEnumerable<string> DoSomething(string arg, params string[] args)
{
    // args null check is not required
    string[] argscopy = new string[args.Length + 1];
    argscopy[0] = arg;
    Array.Copy(args, 0, argscopy, 1, args.Length);
    return argscopy.DoSomething();
}

更新:我现在感谢HugoRune的答案。

3 个答案:

答案 0 :(得分:12)

您可以在params版本中添加其他参数:

public static IEnumerable<string> DoSomething(string firstArg, params string[] moreArgs)

这应该足以让编译器将其与string[]扩展方法区分开来。

正如用户SLaks所建议的那样,如果需要支持具有空params数组的情况,则应在此情况下提供不带任何参数的额外重载:

public static IEnumerable<string> DoSomething()

答案 1 :(得分:3)

迟到的答案:

另一种选择是将两种方法都放在不同的类中。由于在调用扩展方法(具有this参数的方法)时从不使用类名,因此扩展方法可以位于同一名称空间中的任何公共静态类中,没有任何明显的区别。

// contains static methods to help with strings
public static class StringTools
{
    public static IEnumerable<string> DoSomething(params string[] args)
    {
        // do something
    }
}

// contains only extension methods
public static class StringToolsExtensions
{
    public static IEnumerable<string> DoSomething(this string[] args)
    {
        return StringTools.DoSomething(args);
    }
}

这样你就可以避免复制字符串数组,你不需要额外的重载而没有参数,我会说它看起来更干净。我总是将扩展方法和其他静态方法分开来避免混淆。

答案 2 :(得分:1)

  1. 您可以为这两种方法中的一种提供不同的名称。即DoSomething2
  2. 您可以使用一种方法。使用相同参数列表的方法相同;显然他们做同样的事情(因为你没有按照#1给他们不同的名字)。只需将它们结合起来。
  3. 您可以更改其中一种方法的参数列表。 ie(this string [] args,object unusedParameter)