0

我已经编写了几个简单的 GUI 应用程序,但所有的逻辑基本上都写在给定的默认 Form1 类中。

所以我想也许我会把 GUI 逻辑重写到他们自己的类中。例如,FileOpenDialog 的一个类,ListView 的另一个类,等等。这样我的 Form1 类就没有太多不必要的方法,只是用来处理一些基本的东西,在其他 GUI 方法被移动之后可能不会很多。

写了这样的东西作为第一次尝试去某个地方

namespace WindowsFormsApplication1
{
    class OpenFileDialog1 : OpenFileDialog
    {
    }
}

但随后 VS 告诉我我不能从密封类型派生。

我还没有尝试过其他课程,但我可能会在某个时候遇到同样的问题。我没有正确继承它吗?还是我必须使用某种变通方法将每个 GUI 元素分成它们自己的类?

也许这不是一个好方法?

4

3 回答 3

2

一个很好的方法。但不要继承自OpenFileDialog. 只需创建一个简单的类并将内容放在那里。

像这样的东西(只是一个想法):

class FileDialogStuff
{
    static OpenFileDialog dialog = new OpenFileDialog();

    public static string GetFile()
    {
        DialogResult result = dialog.ShowDialog();
        //Do stuff
        return dialog.FileName;
    }
}
于 2012-07-26T18:57:58.317 回答
1

根据 c# 规范,一个密封的类不能被继承到另一个类。你必须直接发起。

如果 OpenFileDialog 是密封类,则不能继承它。

于 2012-07-26T18:48:26.507 回答
1

根据您的澄清评论,听起来您要么想要一些实用程序类或工厂类。也许像下面这样:

public interface IFileOpener
{
    public bool PresentFileOpenDialogToUser();
    public string RequestedFilePath { get; }
}

public class DefaultFileOpener : IFileOpener
{
    private string filePath = default(string);

    public bool PresentFileOpenDialogToUser()
    {
        OpenFileDialog ofd = new OpenFileDialog();
        DialogResult dr = ofd.ShowDialog();
        if (dr == DialogResult.Cancel)
        {
            this.filePath = default(string);
            return false;
        }
        else
        {
            this.filePath = ofd.FileName;
            return true;
        }
    }

    public string RequestedFilePath
    {
        get 
        {
            return this.filePath;
        }
    }
}

public class FileOpenerFactory
{
    public static IFileOpener CreateFileOpener()
    {
        return new DefaultFileOpener();
    }
}

并以您的形式:

    private void btnOpenFile_Click(object sender, EventArgs e)
    {
        IFileOpener opener = FileOpenerFactory.CreateFileOpener();
        if (opener.PresentFileOpenDialogToUser())
        {
            //do something with opener.RequestedFilePath;
        }
    }

你甚至可以用部分类做一些事情,所以在你的主要形式中你有类似的东西

    private void btnOpenFile_Click(object sender, EventArgs e)
    {
        this.OpenMyFile();
    }

在您的部分课程中,您有:

public partial class Form1
{
    private void OpenMyFile()
    {
        IFileOpener opener = FileOpenerFactory.CreateFileOpener();
        if (opener.PresentFileOpenDialogToUser())
        {
            //do something with opener.RequestedFilePath;
        }
    }
}

很多时候,使用部分类作为接口或重点功能的实现非常有用。

于 2012-07-26T19:19:04.533 回答