C# 从单独的类访问表单成员
我需要一些关于实现特定结果的最佳方法的建议...
我的场景...
我有一个 Form1 类,这是我的主窗体,上面有一个图片框。
我有一个称为相机的第二类,它使用事件处理程序从我的网络摄像头抓取帧(位图)。
然后我想以最好的方式将此框架传递到主窗体中的图片框。
目前在主窗体中我有代码:
public static void setPB(Bitmap image)
{
var form = Form.ActiveForm as Form1;
form.pbWebCamDisplay = image;
}
然后在 Camera 类中我使用
Form1.setPB(currentFrame);
这工作正常,但是我不确定这是否是最佳编程实践?是否可以使用自定义事件?
预先感谢
汤姆的任何帮助
I need some advice please on the best way to achieve a particular outcome...
My scenario...
I have a Form1 class, which is my main Form with a picture box on it.
I have a second class called camera that using an event handler grabs a frame (bitmap) from my webcam.
I then want to pass this frame to the picture box in the main form in the best fashion.
At the moment in the main form I have the code:
public static void setPB(Bitmap image)
{
var form = Form.ActiveForm as Form1;
form.pbWebCamDisplay = image;
}
then in the Camera class I use
Form1.setPB(currentFrame);
This works fine, however I wasn't sure if this was best programming practice? Is it possible to use custom events?
Thanks in advance for any help
Tom
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我将在 Camera 类上创建一个方法,该方法拍摄照片并返回 Bitmap 对象。
因此,在按钮的 OnLoad 或 OnClick 中,调用该方法并将返回值设置为 PictureBox...
类似的东西:)
编辑:如果 Camera 类是事件驱动的组件(Camera.NewFrame 事件),请尝试:
(在构造函数中):
(事件处理程序)
I would create a method on the Camera class, which takes the picture and returns a Bitmap object.
So in the OnLoad or in the OnClick of a button, call that method and set the return value to the PictureBox...
Something like that :)
Edit: If the Camera class is an Event driven component (Camera.NewFrame event), try:
(in the constructor):
(event handler)
如果我处于你的位置,我会使用事件。
I would use events if I were in your place.
是的,我想说非常好。您有一个负责处理相机输入的相机类和一个用于表单的私有成员的公共设置器。我不会改变一点点。
这样您就可以将功能的不同职责分为不同的类。不要在 Form 类中处理相机事件,而是按照您正在做的那样进行。
Yeah, I would say is perfectly good. You have a camera class that is in charge of handling the camera input and a public setter for a private member of your form. I would not change a bit.
That way you separate the different responsibilities for the functionalities into different classes. Don't handle the camera events inside the Form class, instead do as you're doing.
毫无疑问,活动是正确的选择。您可以使用它们来实现观察者设计模式。
您当前的实现不是最佳实践 - 它强制 Camera 和 Form 类之间紧密耦合。
Definitely, events are the right choice. You can implement Observer Design Pattern using them.
Your current implementation is not best practice - it forces tight coupling between Camera and Form class.
是什么驱动了使 Camera 类抓取照片的事件?
这很重要。
如果事件是由表单本身触发的,那么您甚至不需要表单中的 PictureBox setter。
顺便说一句,我和豪尔赫·科尔多巴在一起,你只需要一个二传和一个抢球。
奥卡姆剃刀。
what drives the event that make Camera class grab the picture?
This is important.
You don't even need the PictureBox setter in the form if the event is fired by the form itself.
BTW, i'm with Jorge Córdoba, a setter and a grab event are all that you need.
Occam razor.