返回一个接受可变数量参数的函数。

huangapple go评论67阅读模式
英文:

Possible to return a function that takes variable number of parameters

问题

你好,以下是您要翻译的内容:

C#中是否可能返回一个函数,该函数接受可变数量的参数并与"params"关键字相同的方式工作(即具有此签名 `string Combine(params string[] theRest)`)?

这是我的尝试:

private Func<string[], string> CreateCombineFunction(string baseUrl, char delim)
{
    return theRest =>
        baseUrl.TrimEnd(delim) + delim +
        string.Join(delim.ToString(), theRest.Select(r => r!.Trim(delim).ToArray()));
}

使用:

var combineFunction = CreateCombineFunction("http://blabla/", '/');
var combinedStr = combineFunction(new[] { "this", "works" });
// var combinedStr = combineFunction("this", "does", "not", "work");
英文:

Is it possible in C# to return a function that takes a variable number of arguments and works in the same way as params works (i.e., as this signature string Combine(params string[] theRest))?

Here is my attempt:

 private Func&lt;string[], string&gt; CreateCombineFunction(string baseUrl, char delim)
    {
        return theRest =&gt;
            baseUrl.TrimEnd(delim) + delim +
            string.Join(delim.ToString(), theRest.Select(r =&gt; r!.Trim(delim).ToArray());
    }

Usage:

var combineFunction = CreateCombineFunction(&quot;http://blabla/&quot;, &#39;/&#39;);
var combinedStr = combineFunction(new[] { &quot;this&quot;, &quot;works&quot; });
// var combinedStr = combineFunction(&quot;this&quot;, &quot;does&quot;, &quot;not&quot;, &quot;work&quot;);

答案1

得分: 2

Create a delegate that takes a params argument:

创建一个接受 params 参数的委托:
delegate string Foo(params string[] strings);

Use the delegate as a return type:

将委托用作返回类型:
private Foo CreateCombineFunction(string baseUrl, char delim)
{
    return theRest =&gt;
        baseUrl.TrimEnd(delim) + delim +
        string.Join(delim.ToString(), theRest.Select(r =&gt; r.Trim(delim)));
}

Invoke the returned delegate:

调用返回的委托:
var combineFunction = CreateCombineFunction(&quot;http://blabla/&quot;, &#39;/&#39;);
var combinedStr = combineFunction(&quot;this&quot;, &quot;does&quot;, &quot;actually&quot;, &quot;work&quot;);
英文:

Create a delegate that takes a params argument:

delegate string Foo(params string[] strings);

Use the delegate as return type:

private Foo CreateCombineFunction(string baseUrl, char delim)
{
    return theRest =&gt;
        baseUrl.TrimEnd(delim) + delim +
        string.Join(delim.ToString(), theRest.Select(r =&gt; r.Trim(delim)));
}

Invoke the returned delegate:

var combineFunction = CreateCombineFunction(&quot;http://blabla/&quot;, &#39;/&#39;);
var combinedStr = combineFunction(&quot;this&quot;, &quot;does&quot;, &quot;actually&quot;, &quot;work&quot;);

huangapple
  • 本文由 发表于 2023年5月14日 17:26:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76246730.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定