从任何形式调用非静态方法 [英] Call a non-static method from any form
问题描述
我正在使用VS2005中的C#在Win CE6.0下编写应用程序。我的应用程序有多个表单,因此主表单(form1)可以打开设置表单,然后可以打开设置时间和日期表单。所有这些表单都需要调用LogEvent()方法。我最初通过在form1中使用LogEvent()方法'public static'来实现这一点,但是这个方法现在需要调用非静态方法serialPort.Write()而我不能从静态方法执行此操作。任何人都可以建议最好的方法来解决这个问题。我已经看了几个关于这个主题的帖子,但似乎没有一个符合我的情况。
I am writing an application under Win CE6.0 using C# in VS2005. My application has multiple forms, so the main form (form1) may open a "Settings" form and this may then open a "Set Time and Date" form. All of these forms need to call a LogEvent() method. I initially achieved this by making the LogEvent() method 'public static' in form1, but this method now needs to call the non-static method serialPort.Write() and I cannot do this from a static method. Can anyone please suggest the best way to deal with this. I have looked at several posts on this subject, but none seem to fit my circumstances.
推荐答案
作为快速而肮脏的解决方案,你可以制作LogEvent
form1
的非静态成员,然后将form1
的实例传递给另一个表格。
As quick and dirty solution, you could makeLogEvent
a non static member ofform1
and then pass the instance ofform1
to the other forms.
我建议你阅读:如何在C-sharp中声明全局变量? [ ^ ]。 Sergey Alexandrovich Kryuokov解释了如何通过使用单身来访问某些物体。
请阅读其他答案。
I'd suggest to read this: How to declare Global Variable..in C-sharp ?[^]. Sergey Alexandrovich Kryuokov explains ther how to access some objects via using singleton.
Please, read the other answers too.
Don不要把你的测井设施放在任何形式,它不属于那里。使您的日志记录功能静态或应用单例模式。可以在此处找到一个好的单例代码示例: C#深度:实现单例模式 [ ^ ]。
-SA
Don't put your logging facility in any form, it does not belong there. Make your logging function(s) either static or apply the singleton pattern. A good singleton code sample can be found here: C# in Depth: Implementing the Singleton Pattern[^].
—SA
这篇关于从任何形式调用非静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!