外部更新的 Winform 的最佳实践
我想知道将标签公开以便其他类可以更改它们并获得它们的值是否是一个好主意。这是个好主意吗?如果不是的话,那该怎么办呢?
I am wondering whether it is a good idea to make labels public so other classes can change them and get their value. Is this a good idea? If not, how should it be done then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不会公开这个标签。
最好添加一个特定于标签显示内容的公共方法,并让它更新标签。
例如,如果您的标签是“系统状态”标签,您可能需要添加(到您的表单/用户控件):
这允许您稍后更改此信息的显示方式(如果您想使用不同的控件) ),并且还简化了您的 API,因为公共方法对用户来说非常清楚。
I wouldn't make the label public.
It would be better to add a public method that was specific to what the label was displaying, and have it update the label.
For example, if your label was a "System status" label, you might want to add (to your Form/UserControl):
This allows you, later, to change how this information is displayed (in case you want to use a different control), and also simplifies your API, since the public methods are very clear to the user.
这是一个坏主意。 WinForms 留下了许多“做 X 的最佳方法是什么?”的问题。问题开放;最好的答案是遵循既定的模式和实践(这不是 WinForms 特有的)。
阅读 MVP 或 MVC 模式。它们都是高级模式,专注于将特定于 UI 的代码与业务逻辑分开。如果没有这种分离,您的应用程序很快就会成为维护噩梦,并且本应简单的事情会变得更加复杂。
对于您的特定场景,您可能最终会得到一个模型(您的业务逻辑),它使用数据绑定在 WinForms 屏幕上显示其数据。当 UI 发生更改时,模型将接收更改,并且该更改将通过数据绑定传播到 UI。
it's a bad idea. WinForms leaves many "what's the best way to do X?" questions open; and your best answer is to follow established patterns and practices (which aren't WinForms specific).
Read up on the MVP or MVC patterns. They are both high-level patterns which focus on seperating out your UI-specific code from your business-logic. Without this seperation your application can quickly become a maintenance nightmare, and things that should be simple get much more complicated.
For your specific scenario you would likely end up with a Model (your business-logic) which uses databinding to show it's data on the WinForms screen. When a change on the UI occurs it would be the Model that receives the change, and that change would propagate to the UI via databinding.
我建议包装在 setter 属性或方法中,因为如果调用者来自另一个线程,您很可能必须在窗口的主线程上添加日志记录或重新调用之类的操作。我发现在公开允许客户端更新任何图形的功能时,始终使用如下所示的代码会更容易。
I would suggest wrapping in a setter property or method because it's very possible you'll have to do something like add logging or re-call on window's main thread if the caller is from another one. I found it easier to just always use code like the following when exposing functionality that lets clients update anything graphical.