Stu*_*ing 0 c# algorithm design-patterns
我有这个丑陋的代码看起来有点像这样......
TestResult GetFirstTestResult()
{
var result = TestMethod1();
if(result is EmptyResult)
{
result = TestMethod2();
}
if(result is EmptyResult)
{
result = TestMethod3();
}
// ...
if(result is EmptyResult)
{
result = TestMethodN();
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
基本上,我需要运行一些测试,直到找到一个有一些值的测试.
现在虽然上面的代码并不漂亮,但是一个小的(ish)值N是可管理的.可悲的是,就我而言,N可能会变得相当大.
有没有办法用循环写这个,这个伪代码的行...
TestResult GetFirstTestResult()
{
TestResult[] results = {TestMethod1(), TestMethod2(), TestMethod3(), .. TestMethodN()};
return results.First(test=>!test.Result is Emptyresult);
}
Run Code Online (Sandbox Code Playgroud)
这样每个测试方法都在循环中调用,所以实际上只执行了最小数量的测试方法?
TestResult GetFirstTestResult()
{
return new Func<TestResult>[]
{
TestMethod1,
TestMethod2,
TestMethodN
}.Select(t => t())
.FirstOrDefault(r => !(r is EmptyResult)) ?? new EmptyResult();
}
Run Code Online (Sandbox Code Playgroud)
它依次调用每个方法,直到找到结果不是类型的方法EmptyResult并返回该方法.如果没有找到这样的结果,则返回new EmptyResult()
像这样的东西?显然我没有你所有的代码所以无法验证正确性,但你应该能够根据需要进行修改:
List<Func<TestResult>> methods = new List<Func<TestResult>>() { TestMethod1, TestMethod2, TestMethod3 };
foreach(var f in methods)
{
if(f().Result != EmptyResult)
{
break; //or something else
}
}
Run Code Online (Sandbox Code Playgroud)