在 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");
创建一个接受参数参数的委托:
delegate string Foo(params string[] strings);
使用委托作为返回类型:
private Foo CreateCombineFunction(string baseUrl, char delim)
{
return theRest =>
baseUrl.TrimEnd(delim) + delim +
string.Join(delim.ToString(), theRest.Select(r => r.Trim(delim)));
}
调用返回的委托:
var combineFunction = CreateCombineFunction("http://blabla/", '/');
var combinedStr = combineFunction("this", "does", "actually", "work");