如何同时编译这两种方法?
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的答案。
答案 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)
DoSomething2