如何在C#中将一个表单属性继承到另一个表单 [英] how to inherit one form properties to another form in C#
本文介绍了如何在C#中将一个表单属性继承到另一个表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好
请任何人帮助我......
i目前在C#
工作,我希望得到关于Page继承的总和帮助
所以我创建了
From1:
在这个表格中我写了一个函数le
public void MyFunction()< br />
{< br />
.............< br />
.... ..........< br />
..............< br />
}
我希望以另一种形式调用该函数le
Form2< br />
{< br />
MyFunction();< br />
}
谢谢.........
please快速
解决方案
如果我理解正确你需要做的就是在第二种形式中创建第一种形式的实例,或者将第一种形式的引用传递给第二种形式。
// 要在第一个表单中创建第二个表单的实例,请执行此操作,即
Form2 form2 = new Form2();
form2.MyFunction();
// 将第一个表单的引用传递给第二个表单,即
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
Form2 form2 = new Form2( this );
}
public MyFunction()
{
// 做东西
}
}
public partial class Form2:Form
{
Form1 mainForm;
public Form2(Form1 mainForm)
{
InitializeComponent();
this .mainForm = mainForm;
// call form1 MyFunction()
mainForm.MyFunction();
}
}
解决方案2是正确的,但是,如果共享Form1中的方法,则应考虑实现一个公共类,可以在所有表单之间共享。单独的程序集将为您提供更容易的维护和可扩展性。
这是一个关于表单协作的流行问题。最强大的方法是在表单类中实现适当的接口。为表单使用部分类声明特别方便。请参阅我过去的解决方案以获取更多详细信息:如何以两种形式复制列表框之间的所有项目 [ ^ ]。
-SA
hello
please any one help me...
i currently work in C#
and i want sum help about Page inheritance
so i create
From1:
in this form i have written one Function l.e
public void MyFunction()<br /> {<br /> .............<br /> ..............<br /> ..............<br /> }
Than i want call that function in another form l.e
Form2<br /> {<br /> MyFunction();<br /> }
thank you.........
please quickly
解决方案
If I understand correctly all you will need to do is create an instance of the fist form in the second form or pass a reference of the first form to the second form.
//To create instance of second form inside first form do this i.e. Form2 form2 = new Form2(); form2.MyFunction();
//to pass a reference to first form into the second form i.e. public partial class Form1 : Form { public Form1() { InitializeComponent(); Form2 form2 = new Form2(this); } public MyFunction() { // do stuff } } public partial class Form2 : Form { Form1 mainForm; public Form2(Form1 mainForm) { InitializeComponent(); this.mainForm = mainForm; // call form1 MyFunction() mainForm.MyFunction(); } }
Solution 2 is correct, however, if the method in Form1 is shared you should consider implementing a common class that can be shared between all forms. An separate assembly will provide you with easier maintenance and extensibility.
This is a popular question on form collaboration. The most robust approach is implementing of an appropriate interface in a form class. It is especially convenient to use partial class declaration for a form. Please see my past solution for more detail: How to copy all the items between listboxes in two forms[^].
—SA
这篇关于如何在C#中将一个表单属性继承到另一个表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文