gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:39:21 25 4
gpt4 key购买 nike

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

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现在的答案。

最佳答案

您可以在 params 版本中添加一个额外的参数:

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

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

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

public static IEnumerable<string> DoSomething()

关于c# - 字符串数组和参数的扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com