Mar*_*son 2 c# code-duplication c#-5.0
我有一些重复的代码,但不确定简化它的最佳方法.
private void CheckData(long PKID, int ExpectedResult, string Server)
{
var a = _ARepo.GetAll();
var b = _BRepo.GetAll();
if(Server == "A")
{
a.Find(x => x.PKID == PKID).Result.ShouldBe(ExpectedResultId);
}
if (Server == "B")
{
b.Find(x => x.PKID == PKID).Result.ShouldBe(ExpectedResultId);
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个单元测试项目,我正在使用该Shouldly库.任何想法都赞赏.
private void CheckData(long PKID, int ExpectedResult, string Server)
{
//Setting to empty because I don't know what happens if it is not "A" nor "B"
IEnumerable<YourType> data = Enumerable.Empty<YourType>();
if(Server == "A")
data = _ARepo.GetAll();
else if(Server == "B")
data = _BRepo.GetAll();
data.Find(Find(x => x.PKID == PKID).Result.ShouldBe(expectedId);
}
Run Code Online (Sandbox Code Playgroud)
如果Server值只能是A或者B你可以用一个if else或更好的?:运算符替换它然后它看起来像:
var data = Server == "A" ? _ARepo.GetAll() : _BRepo.GetAll();
data.Find(Find(x => x.PKID == PKID).Result.ShouldBe(expectedId);
Run Code Online (Sandbox Code Playgroud)
在两者都Repo实现相同接口的情况下,更好的设计将获得IRepo作为函数的参数.这样,该函数只有一个角色 - 即检查数据(而不是决定要检查的数据)