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

hIp*_*pPy 9 c# extension-methods params

我怎样才能将这两种方法都编译好?

public static IEnumerable<string> DoSomething(params string[] args)
{ // do something }
public static IEnumerable<string> DoSomething(this string[] args)
{ // do something }
Run Code Online (Sandbox Code Playgroud)

我得到这个编译错误:

Type 'Extensions' already defines a member called 'DoSomething' with the same parameter types Extensions.cs
Run Code Online (Sandbox Code Playgroud)

所以我可以这样做:

new string[] { "", "" }.DoSomething();
Extensions.DoSomething("", ""); 
Run Code Online (Sandbox Code Playgroud)

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

Extensions.DoSomething(new string[] { "", "" });
Run Code Online (Sandbox Code Playgroud)

更新:根据OR 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();
}
Run Code Online (Sandbox Code Playgroud)

更新:我现在喜欢HugoRune的回答.

O. *_*per 12

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

public static IEnumerable<string> DoSomething(string firstArg, params string[] moreArgs)
Run Code Online (Sandbox Code Playgroud)

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

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

public static IEnumerable<string> DoSomething()
Run Code Online (Sandbox Code Playgroud)

  • 以及无参数版本. (5认同)
  • 非常好的解决方案,+ 1 (3认同)

Hug*_*une 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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