英文:
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<string[], string> CreateCombineFunction(string baseUrl, char delim)
{
return theRest =>
baseUrl.TrimEnd(delim) + delim +
string.Join(delim.ToString(), theRest.Select(r => r!.Trim(delim).ToArray());
}
Usage:
var combineFunction = CreateCombineFunction("http://blabla/", '/');
var combinedStr = combineFunction(new[] { "this", "works" });
// var combinedStr = combineFunction("this", "does", "not", "work");
答案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 =>
baseUrl.TrimEnd(delim) + delim +
string.Join(delim.ToString(), theRest.Select(r => r.Trim(delim)));
}
Invoke the returned delegate:
调用返回的委托:
var combineFunction = CreateCombineFunction("http://blabla/", '/');
var combinedStr = combineFunction("this", "does", "actually", "work");
英文:
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 =>
baseUrl.TrimEnd(delim) + delim +
string.Join(delim.ToString(), theRest.Select(r => r.Trim(delim)));
}
Invoke the returned delegate:
var combineFunction = CreateCombineFunction("http://blabla/", '/');
var combinedStr = combineFunction("this", "does", "actually", "work");
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论