从窗体/控件继承并编写模块化代码



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

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

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

namespace WindowsFormsApplication1
{
    class OpenFileDialog1 : OpenFileDialog
    {
    }
}

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

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

也许这不是一个好方法?

这是一个很好的方法。但不要从OpenFileDialog继承。只需创建一个简单的类并将这些东西放在那里。

类似的东西(只是一个想法):

class FileDialogStuff
{
    static OpenFileDialog dialog = new OpenFileDialog();
    public static string GetFile()
    {
        DialogResult result = dialog.ShowDialog();
        //Do stuff
        return dialog.FileName;
    }
}

根据您的澄清评论,听起来您要么想要一些实用程序类,要么想要一些工厂类。也许如下所示:

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;
        }
    }
}

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

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

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

最新更新