这是来自编程测试,所以我确信有更好的方法来做到这一点,但问题需要这个特定的答案。
我有一个 Result 方法,它简单地匹配一个谓词并返回一个 bool 值,并且有问题的谓词检查一个字符串数组以报告是否有任何字符串超过长度 5。
static bool Result<T>(T[] values, Func<T, bool> predicate)
{
if (values.Where<T>(predicate).Count() > 0)
return true;
else
return false;
}
static bool StringLengthLessThan5(string str)
{
return str.Length < 5;
}
最后这个是这样用的——
bool val2 = Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, StringLengthLessThan5);
这按预期工作,但是现在我需要使用相同类型的代码但参数化 Func 以允许字符串长度的动态值,即我的 Func<string,bool>
现在需要 Func<string,int,bool>
static bool StringLengthLessThanGivenNumber(string str,int length)
{
return str.Length < length;
}
或者,
static Func<string, int, bool> FuncForDynamicStringlength = (s, i) => s.Length < i;
我的问题是,本着保持新 Func 的调用代码不变的精神,即我仍然想使用 -
Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, StringLengthLessThanGivenNumber);
但是,我该如何传递参数呢?
Func 现在需要 2 个参数,第一个是字符串,第二个是 int,我如何传递第一个参数?我可以传递 int 长度进行比较,但我对第一个参数感到困惑。
我意识到我可以遍历我的 string[] 并像这样在 foreach 中调用 Func(我知道这在这个特定实例中没有意义,因为我正在覆盖 bool 的值,但我确定你明白我的问题)-
foreach(string str in new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" })
{
bool val3_1 = StringLengthLessThanGivenNumber(str, 5);
}
但如果可能的话,我想使用我的原始代码。
最佳答案
只需将谓词包装到 lambda 表达式中,然后使用变量或常量传递所需的长度,如下所示:
int len = 5;
bool val1 = Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, x => StringLengthLessThanGivenNumber(x, len));
bool val2 = Result(new string[5] { "asdf", "a", "asdsffsfs", "wewretete", "adcv" }, x => StringLengthLessThanGivenNumber(x, 5));
解决这个问题的另一种方法是为 string
集合定义扩展方法。
public static class StringCollectionExtensions
{
public static bool HasLengthLessThan(this IEnumerable<string> collection, int length)
{
return collection.Any(x => x.Length < length);
}
}
然后你可以像这样使用它:
var testStrings = new string[5] {"asdf", "a", "asdsffsfs", "wewretete", "adcv"};
bool val3 = testStrings.HasLengthLessThan(6);
关于c# - 在 C# 中将多个参数传递给 Func<>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44524193/