从项目中的不同形式调用函数 [英] Calling a function from different forms in a project

查看:84
本文介绍了从项目中的不同形式调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有一个函数可以提取不同的条目.实际上,它是从SqlServer DB中的各个表中获取这些条目的.这些条目然后显示在dataGrid的字段中.我想以其他形式使用该函数,而无需重写整个代码.

我该怎么做,如何将这些条目介绍到functoin中?

非常感谢!

I have a function in my project which fetches different entries. Actually it gets these entries from various tables in a SqlServer DB. These entries are then shown in the fields of a dataGrid. I want to use the function in other forms without rewriting the whole code.

How can I do this and how can I introduce the entries to the functoin?

Thanks a lot!

推荐答案

如果您有通用功能,请将其移至帮助程序类,而不是以表格形式出现.

但是仍然要以其他形式调用这些函数,然后创建该表单的实例并调用那些公共函数(注意:如果这些函数使用表单全局/实例成员,则需要确保已初始化那些成员).

这是使用新表单的一种可选的分离方法,它会在调用者表单上进行回调.

将委托用于表单可重用性-依赖注入原理 [ ^ ]
If you have common functions move them to a helper class instead of having it in forms.

But still if you want to call the functions in other form, then create instance of that form and call those public functions (Note: If those functions use form global/ instance members, need to make sure those members are initialized).

Here is an optional decoupled way to use a new form and it call back on the caller form.

Use of delegates for form reusability- Dependency injection principle[^]


使用依赖项注入(以及同名的设计模式)是一种很好的众所周知的方法.

我更喜欢一种更简单的方法.您可以创建一个在两种形式中都可见的接口,并通过要调用的方法的形式来实现该接口.很好的一点是,您可以利用部分表单声明的优势.您可以创建另一个文件,并在继承列表中添加您的接口(但不能添加Form-在其他部分声明继承列表中声明).您也不需要将接口添加到部分声明的其他文件中.

仅将接口引用传递给表单以调用您的方法,而不传递给表单.这样,您可以将接口与其实现隔离.您不需要公开您的方法,也无需从另一种形式大量访问一种形式.

Using a dependency injection (and a design pattern of the same name) is a good well-known method.

I prefer a different method which I find a bit simpler. You can create an interface visible in both forms and implement it by the form which methods you want to call. Good thing about it that you can take benefit of partial form declaration. You can created yes another file and in inheritance list add you interface (but not Form — it is declared in other partial declaration inheritance list). You also don''t need to add your interface to other files of partial declaration.

Pass just the interface reference to the form to be calling your methods, not reference to the form. In this way, you isolate interface from its implementation. You don''t need to make your methods public and pass to much access to one form from another.

//to avoid making implementation of interface methods/properties public, use this form:
void MyInterface.MyMethod(/*...*/) { /*...*/ }

//not this:
public void MyMethod(/*...*/) { /*...*/ }



在大多数情况下,接口实现的第一种方法是最好的,而不仅仅是表单之间的接口.

—SA



First method of interface implementation is the best in most cases, not just for interfacing between forms.

—SA


这篇关于从项目中的不同形式调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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