c# - 使 if 语句看起来更好

标签 c# if-statement

我怎样才能让它看起来更好:

lblTotalWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem) * 1024 + " kb";    // Total world size
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem))                  // World itself
{
    lblWorldSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem) * 1024 + " kb";
}
else
{
    lblWorldSize.Text = "Couldn't find world.";
}
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem + "_nether"))      // Nether
{
    lblNetherSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem + "_nether") * 1024 + " kb";
}
else
{
    lblWorldSize.Text = "Couldn't find world.";
}
if (Directory.Exists(_worldsDirectory + selectedItem + "\\" + selectedItem + "_the_end"))     // The End
{
    lblTheEndSize.Text = GetDirectorySize(_worldsDirectory + selectedItem + "\\" + selectedItem + "_the_end") * 1024 + " kb";
}
else
{
    lblWorldSize.Text = "Couldn't find world.";
}

看起来真的很乱,我似乎找不到任何类似的问题。

最佳答案

好吧,这里有几件事可以提供帮助:

  • 辅助方法(您每次都执行从“路径”到“大小字符串”的相同转换)
  • 条件运算符
  • 提取公共(public)局部变量

像这样:

// Note that _worldsDirectory must be an absolute path)
string prefix = Path.Combine(_worldsDirectory, selectedItem, selectedItem);
lblWorldSize.Text = GetDirectorySizeOrDefault(prefix, "Couldn't find world");
lblNetherSize.Text = GetDirectorySizeOrDefault(prefix + "_nether",
                                               "Couldn't find _nether");
lblTheEndSize.Text = GetDirectorySizeOrDefault(prefix + "_the_end",
                                               "Couldn't find _the_end");

...

static string GetDirectorySizeOrDefault(string directory, string defaultText)
{
    return Directory.Exists(directory)
        ? GetDirectorySize(directory) * 1024 + " kb"
        : defaultText;
}

请注意,我已经更正了以下事实:您的原始代码总是在错误时分配给 lblWorldSize.Text - 我认为这不是故意的。

关于c# - 使 if 语句看起来更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11693419/

相关文章:

mysql - SQL if 语句

c++ - if..else.. 语句未输出预期结果。 while..循环问题?

c# - 如何正确通知数据绑定(bind)控件复合属性具有新值?

c# - 报表查看器 - 请求 SqlClientPermission 类型的权限失败

c++ - 为什么比较结果不符合预期?

c - (x < 8) 当 x = -3 时返回 false( double )

c# - Linq-to-sql 错误 : 'int[]' does not contain a definition for 'Contains'

c# - 动态网址路由

C# BackgroundWorker 并行调用 DoWorkEventHandler

if-statement - IF 函数 - 重新格式化组件