使用类来组织代码?

发布于 2024-09-25 05:54:30 字数 261 浏览 6 评论 0原文

目前我的 Form1 代码非常繁重,主要充满了菜单和控件事件。我想做的一件事是以某种方式组织它,这样我就可以展开或折叠“相关代码”(在 Visual Studio 中)。

我的第一次尝试是将与主菜单相关的代码放在一个名为“MainMenu”的嵌套类中,该类位于 Form1 类中,这样当我不需要它时,我可以简单地折叠该嵌套类。这导致了各种各样的问题(即我找不到在这个嵌套类中设置主菜单的方法)。

我缺少一个更简单的解决方案吗?或者有人可以解释一下为什么我的嵌套类想法是错误的?

At the moment my Form1 code is extremely heavy, mainly full of menu and control events. One thing I would like to do is organize it in some way, so I could expand or collapse "related code" (in Visual Studio).

My first attempt at this was to put code relating to the main menu, for example, inside a nested class called "MainMenu", which was within the Form1 class, so that I could simply collapse the nested class when I don't need it. This resulted in all sorts of problems (i.e. I couldn't find a way to set up the main menu inside this nested class).

Is there a simpler solution to this that I'm missing? Or can someone shed some light on why my nested class idea is faulty?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

云雾 2024-10-02 05:54:30

虽然@testalino的答案确实满足了您的要求,但我想说您的真正问题可能与代码设计有关。很可能表单类包含的代码比应有的多,并且其中一些代码应该移至其他类中。

如果以一种好的方式完成,这可能会给您带来一些好处:

  • 当各种函数对通过参数传递给方法的数据进行操作并返回值而不是直接在中获取和设置值时,您可能会获得更多封装(并且耦合更少)的行为。用户界面控件。
  • 您可能会获得更可测试的代码库(您确实有单元测试,对吧?)。
  • 由于代码分布在多个不同的代码文件中,因此多个人可以更轻松地协作编写代码。这减少了合并冲突(您确实有源代码控制系统,对吧?)。如果你独自做某件事,这一点可能不太适用,但无论如何,养成这个习惯也没什么坏处。

While @testalino's answer certainly does what you ask for, I would say that your real problem is probably related to code design. Chances are that the form class simply contains more code than it should, and that some of it ought to move into other classes.

If done in a good way, this might give you some benefits:

  • You will likely get more encapsulated (and less coupled) behavior, when various functions operates on data passed to the methods through parameters and return values instead of fetching and setting values directly in UI controls.
  • You might get a more testable code base (you do have unit tests, right?).
  • It will be easier for several persons to collaborate on the code, since the code is spread across several different code files. This reduces merging conflicts (you do have a source control system, right?). This point may not be as applicable if you are working on something alone, but it doesn't hurt to have this habit anyway.
倚栏听风 2024-10-02 05:54:30

您可以使用#region 和#endregion 来组织类中的代码。然后这些区域是可折叠的。

You can use #region and #endregion to organize code within a class. These regions are then collapseable.

看海 2024-10-02 05:54:30

我建议您使用用户控件来封装一些表单的行为。我想,这是目前您可以使用的最简单的解决方案。您只需选择一些用户界面并将其提取到用户控件并定义一些可从表单访问的公共属性。

将所有处理程序保留在 Form.cs 中是一种非常糟糕的做法。你必须避免它,因为它是不可维护的(我见过很多这样的代码,并且在后期阶段,添加或更改功能被证明在不破坏任何内容的情况下是不可能的,更不用说在不影响应用程序工作方式的情况下更改 UI 了)。

将来,您可能想要尝试不同的方法将 UI 与应用程序逻辑分离,例如探索 MVP/MVC 模式。

I suggest you using User Controls to encapsulate some of Form's behavior. This is the simplest solution available for you right now, I guess. You just pick some piece of user interface and extract it to user control and define some public properties accessible from the form.

Keeping all handlers in Form.cs is a bad, bad practice. You must avoid it because it's unmaintanable (I've seen much code like that, and at later stages adding or changing functionality is proven to be impossible without breaking anything, let alone changing the UI without affecting the way app works).

In future, you may want to try different approaches to separation UI from application logic, e.g. explore MVP/MVC patterns.

流殇 2024-10-02 05:54:30

如果您的表单变得如此庞大和复杂,以至于您突然希望以某种方式组织它,则强烈暗示需要重构,这将提高代码的可读性、可测试性和可维护性。您实际重构的方式取决于您的实际代码。

它是一个有很多控件的表单吗?考虑将其拆分为单独的用户控件,其中每个控件都显示域数据的某个方面。您是否有很多交互逻辑,对很多事件做出反应?也许引入某种控制器或事件聚合器。

有许多众所周知的模式可以帮助您组织 UI 和域代码。 本系列 讨论的正是这一点,并向您介绍 MVC、MVP、EventAggregator 等模式。它根据您的需要讨论了 Windows 窗体上下文中的模式。

If your form has become so big and complex that you suddenly desire to organize it in some way it is a strong hint towards the need of refactoring, which will improve readability, testability and maintainablity of your code. How you actually refactor depends upon your actual code.

Is it a form that has a lot of controls? Think about splitting it up in separate UserControls where each of them displays a certain aspect of your domain data. Do you have a lot of interaction logic, reacting to a lot of events? Maybe introduce a some sort of Controller or EventAggregator.

There are a lot of well known patterns that can help you organize your UI and domain code. This series talks about just that and introduces you to patterns MVC, MVP, EventAggregator and much more. It discusses the patterns in the context of windows forms just as you need it.

逆蝶 2024-10-02 05:54:30

使用partial class 关键字将您的类拆分为多个文件。

Use the partial class keyword in order to split your class into several files.

一口甜 2024-10-02 05:54:30

我同意其他答案所说的关于在 #regions 中将类似的事件处理程序分组在一起是可靠的,因为考虑到大量的事件。此外,如果处理程序中的代码本身也很庞大,您可能需要考虑将它们重构为逻辑业务逻辑类。示例:

之前的伪代码:

private void SomeButton_Click(...)
{
    using (FileStream fs = ...)
    {
        fs.Write(some form data);
        fs.Write(some more form data);
    }

    DoMoreBusinessLogicStuff();
    ...
    // lots more stuff
    ...
}

之后的伪代码:

private void SomeButton_Click(...)
{
    IBusinessObject obj = new BusinessObject(injectable form data);

    using (IPersistence store = new FilePersistence(...))
    {
        obj.Persist(store);
    }

    obj.DoBusinessRules();
}

这应该将业务、持久性和支持逻辑移动到它们自己的类中,并将事件处理程序保留为仅设计用于收集 UI 输入并将其传递的轻量级 shell。

I agree with what the other answers say about grouping alike event handlers together in #regions is solid given a massive number of events. In addition, if the code itself in the handlers is voluminous as well, you might want to think of refactoring those into logical business logic classes. Example:

pseudocode before:

private void SomeButton_Click(...)
{
    using (FileStream fs = ...)
    {
        fs.Write(some form data);
        fs.Write(some more form data);
    }

    DoMoreBusinessLogicStuff();
    ...
    // lots more stuff
    ...
}

pseudocode after:

private void SomeButton_Click(...)
{
    IBusinessObject obj = new BusinessObject(injectable form data);

    using (IPersistence store = new FilePersistence(...))
    {
        obj.Persist(store);
    }

    obj.DoBusinessRules();
}

This should move business, persistence and support logic to their own classes and leave your event handlers as lightweight shells designed only to gather UI input and pass it along.

情域 2024-10-02 05:54:30

嵌套类通常不受欢迎,因为它只是对上帝类的轻微升级,而且封装和代码重用也相当模糊。

应该致力于将您实际拥有的对象表达为代码中的单独业务类:一个类,一个文件。您不这样做有什么特别的原因吗?

Nested classes are generally frowned upon as being only a slight upgrade from god-classes for one thing, and encapsulation and code reuse being pretty murky.

You should be aiming to express the objects you actually have as individual business classes within your code: one class, one file. Is there any particular reason you aren't doing this?

故事还在继续 2024-10-02 05:54:30

根据它正在执行的代码类型,将取决于您可以将其移动到哪里。

如果它处理数据代码,那么您可以将其移到不同名称空间中的单独类中,将处理后的数据返回到控件以允许数据绑定等。

如果 Form1 的代码变得非常繁重,那么这是因为您有太多的工作要做在 Form1 中?你能把它分解成另一种/新的形式吗?

Depending on the type of code it is doing will depend on where you can move it.

If its processing data code then you can move this out into separate classes in a different namespace returning the processed data to controls to allow for data binding etc.

If Form1 is getting very heavy with code then is this because you've got too much going on in Form1? Could you break it out into a different/new form?

日记撕了你也走了 2024-10-02 05:54:30

您可以使用可折叠的摘要,但我认为这更多的是为了向其他开发人员提供信息,但始终是良好的做法!

在 VB 中:

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>

在 C# 中

/// <summary>
///
/// </summary>
/// <remarks></remarks>

You could use the summary which is collapsible but I think this is more intended for providing other developers with information, always good practice though!

In VB:

''' <summary>
''' 
''' </summary>
''' <remarks></remarks>

In C#

/// <summary>
///
/// </summary>
/// <remarks></remarks>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文