对于C#,我还是个新手,我想知道如何才能最小化这些代码。
这就是我到目前为止所知道的:
private void CheckFiles()
{
if (!File.Exists(ProgramLocation + "\\Server Files\\" + "Bukkit.jar"))
{
DownloadBukkitJar();
}
else
{
Close();
}
if (!File.Exists(ProgramLocation + "\\dlls\\" + "HtmlAgilityPack.dll"))
{
DownloadHtmlAgilityPackDll();
}
else
{
Close();
}
}那么,我如何才能用更少的代码实现这一点呢?
发布于 2012-04-03 17:53:51
private void CheckFile(string path, Action actionIfMissing)
{
if (!File.Exists(path))
{
actionIfMissing();
}
else
{
Close();
}
}
public void CheckFiles()
{
var bukkitPath = Path.Combine(ProgramLocation, String.Format("{0}{1}{2}", "Server Files", Path.DirectorySeparatorChar, "Bukkit.jar");
CheckFile(bukkitPath, DownloadBukkitJar);
var htmlAgilityPackPath = Path.Combine(ProgramLocation, String.Format("{0}{1}{2}", "dlls", Path.DirectorySeparatorChar, "HtmlAgilityPack.dll");
CheckFile(htmlAgilityPackPath, DownloadHtmlAgilityPackDLL);
}注意-在对文件路径进行硬编码时要小心,如果要构建路径,或者使用Path.Combine组合路径时,则应使用Path.DirectorySeparatorChar。这将确保您的路径是特定于平台的,这将使您的代码更容易移植。我已经更新了示例,以演示如何做到这一点。
发布于 2012-04-03 17:51:45
我不确定close()或downloadfunction是做什么的,但我个人的目标是:
private void CheckFiles()
{
DownloadIfNeeded(ProgramLocation + "\\Server Files\\" + "Bukkit.jar");
DownloadIfNeeded(ProgramLocation + "\\dlls\\" + "HtmlAgilityPack.dll");
}
private void DownloadIfNeeded(string s)
{
if (!File.Exists(s))
{
DownloadFile(s);
}
else
{
Close();
}
}发布于 2012-04-03 17:52:04
根据您的喜好和编码风格指南,以下可能是一种合理的尝试:
private void CheckFiles()
{
bool bukkit = File.Exists(string.Format("{0}\\Server Files\\Bukkit.jar", ProgramLocation));
bool htmlap = File.Exists(string.Format("{0}\\dlls\\HtmlAgilityPack.dll", ProgramLocation));
if (!bukkit) DownloadBukkitJar();
if (!htmlap) DownloadHtmlAgilityPackDll();
if (bukkit || htmlap) Close();
}笔记
我假设两次调用Close在使用String.Format (一个代码清晰度高于性能的示例)时实际上不是meaningful
https://stackoverflow.com/questions/9990770
复制相似问题