将同一个实例传递给所有表单 [英] Passing the same instance to all forms

查看:56
本文介绍了将同一个实例传递给所有表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在form1中有一个变量,我想使用c#将其传递给form2和其他形式,我该怎么做?

谢谢

[edit]拼写和大写字母-OriginalGriff [/edit]

I have a variable in form1 I want to pass it to form2 and other forms using c# how can i do this??


Thank you

[edit]Just spelling and capitalization - OriginalGriff[/edit]

推荐答案

大量方法:
好:
1)Form2中的公共财产;从Form1设置它
2)在Form1中带有参数的事件;订阅Form2中的事件

不好:
1)Form2中的公共领域;在Form1中设置它
2)Form1中的公共字段;在Form2中抢到它
3)Form1或Form2中的静态字段/属性,其他中的set/grab.

还有其他方法,但涵盖了大多数方法.
Loads of ways:
Good:
1) Public Property in Form2; set it from Form1
2) Event with argument in Form1; subscribe to event in Form2

Bad:
1) Public field in Form2; set it in Form1
2) Public field in Form1; grab it in Form2
3) Static field/property in either Form1 or Form2, set/grab in other.

There are others, but that covers most ways.


创建一个包含静态字符串变量的静态全局类,并在应用程序中的任何位置进行设置/获取.当然,OOZ(面向对象的狂热者)通常不赞成全局静态var,但是,嘿,它可以完成工作,而且效率很高.
Create a static global class that contains a static string variable, and set it/get it from anywhere in the application. Of course, global static vars are generally frown upon by OOZ (object oriented zealots), but hey, it gets the job done, and it''s efficient.


创建一个静态对象(单个实例(如果需要),则可以使用任何形式,然后再使用该静态变量对其进行调用.

这将确保您可以从任何地方访问相同的表单对象.

如果是VB.NET,则可以使用Form1(类的名称)隐式访问Application对象.
Create a Static object (single instance if you want) outside any form and later call it using that Static Variable.

This will ensure that you will access the same form object from anywhere.

In case of VB.NET, you might use Form1(name of the class) to implicitly access the Application object.


这篇关于将同一个实例传递给所有表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆