我有以下丑陋的if语句,它是从IOC容器中提取的类的一部分:
protected virtual void ExecuteSourceControlGet(IBuildMetaData buildMetaData, IPackageTree componentTree)
{
if ((buildMetaData.RepositoryElementList != null) && (buildMetaData.RepositoryElementList.Count > 0))
{
componentTree.DeleteWorkingDirectory();
foreach (var repositoryElement in buildMetaData.RepositoryElementList)
{
repositoryElement.PrepareRepository(componentTree, get).Export();
}
}
if((buildMetaData.ExportList != null) && (buildMetaData.ExportList.Count > 0))
{
var initialise = true;
foreach (var sourceControl in buildMetaData.ExportList)
{
log.InfoFormat("\nHorn is fetching {0}.\n\n".ToUpper(), sourceControl.Url);
get.From(sourceControl).ExportTo(componentTree, sourceControl.ExportPath, initialise);
initialise = false;
}
}
log.InfoFormat("\nHorn is fetching {0}.\n\n".ToUpper(), buildMetaData.SourceControl.Url);
get.From(buildMetaData.SourceControl).ExportTo(componentTree);
}
Run Code Online (Sandbox Code Playgroud)
我消除if语句的常用方法是为每个条件创建一个子类.
这个例子的不同之处是:
任何建议都非常欢迎.
Jon*_*eet 14
我不确定你为什么要删除if语句 - 并且使用继承它似乎超过顶部.您可能想要为重复的集合代码创建扩展方法:
public static bool HasElements<T>(this ICollection<T> collection)
{
return collection != null && collection.Count != 0;
}
Run Code Online (Sandbox Code Playgroud)
这使您可以将条件更改为:
if (buildMetaData.RepositoryElementList.HasElements())
Run Code Online (Sandbox Code Playgroud)
和
if (buildMetaData.ExportList.HasElements())
Run Code Online (Sandbox Code Playgroud)
这是一个稍微简单的IMO.如果最终存在更多逻辑,您可能还想将两个块分成不同的方法.除此之外,我不担心.
哦,还有另一种扩展方法,如果你需要关心你是否有元素,这将无济于事,但如果你只想做一个零安全的话会有所帮助foreach:
public static IEnumerable<T> EmptyIfNull<T>(this IEnumerable<T> source)
{
return source ?? Enumerable.Empty<T>();
}
Run Code Online (Sandbox Code Playgroud)
(并不是因为内联使用空合并运算符而节省了很多,不可否认......)