简体   繁体   English

C#:我是否正在验证文件类型并以正确的方式使用goto?

[英]C#: Am i validating filetype and using goto in a right manner?

i have code to save a file like 我有代码来保存文件

SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "Text files|*.txt";

SaveDialog:
if ((bool)dialog.ShowDialog()) {
    if (System.IO.Path.GetExtension(dialog.FileName) != ".txt") {
        MessageBox.Show("You must select a .txt file");
        dialog.FileName = "";
        goto SaveDialog;
    }
    File.WriteAllText(dialog.FileName, txtEditor.Text);
}

i read that i should not use goto. 我读到我不应该使用goto。 i could use do/while and check that a valid extension was selected but that will add alot of unnecessary code. 我可以使用do / while并检查是否选择了有效的扩展名,但这会添加很多不必要的代码。 i find this neater. 我觉得这更整洁。 or is there a better/more correct way? 还是有更好/更正确的方法?

using (SaveFileDialog dialog = new SaveFileDialog())
{
    dialog.Filter = "Text files|*.txt";
    while(dialog.ShowDialog() == DialogResult.OK)
        if (System.IO.Path.GetExtension(dialog.FileName).ToLowerInvariant() != ".txt")
            MessageBox.Show("You must select a.txt file");
        else // file is ok
        {
            File.WriteAllText(dialog.FileName, txtEditor.Text);
            break;
        }
 }

I would suggest the following: 我建议以下内容:

using (SaveFileDialog dialog = new SaveFileDialog()) {
    dialog.Filter = "Text files|*.txt";

    while (true) {
        if (dialog.ShowDialog() == DialogResult.OK) {
            if (!System.IO.Path.GetExtension(dialog.FileName).Equals(".txt", StringComparison.InvariantCultureIgnoreCase)) {
                MessageBox.Show("You must select a .txt file");
            }
            else {
                File.WriteAllText(dialog.FileName, txtEditor.Text);
                break; 
            }          
        }
        else break;
    }
}

While there are legitimate reasons for using the goto statement, in this case it can be avoided and replaced with a more readable solution. 尽管有合理的理由使用goto语句,但是在这种情况下可以避免使用,而是用更具可读性的解决方案代替。

Note also that you should not cast DialogResult (the return value of ShowDialog()) to bool. 还要注意,您不应该将DialogResult(ShowDialog()的返回值)强制转换为bool。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM