C#窗體傳值實例匯總
本文實例匯總了C#窗體傳值的方法。分享給大家供大家參考。具體方法如下:
1.靜態(tài)變量傳值,非常簡單適合簡單的非實例的
public static int A;
}
public class form2:Form{
form1.A=1;
}
2.委托傳值
public int A{get;set;}
public static Action<int> setIntADelForClass;//類的委托
public Action<int>setIntADel //實例的委托
public void setintA(int a){
A=a;
}
public void form_load(object sender, EventArgs e){
setIntADelForClass=setIntA;
setIntADel =setIntA;
}
}
public class form2:Form{
public void setFom1IntA{
form1.setIntADelForClass(10);//通過類的委托將form1 的A變量設(shè)置為10
form1 fm1=new form1();
fm1.setIntADel(12);//通過實例的委托將新實例fm1的A變量設(shè)置為12
}
}
3.使用onwer屬性,適合對話框之間的傳值
public int A{get;set;}
private void button1_click(object sender, EventArgs e){
A=10;
Form2 fm2=new Form2();
fm2.ShowDialog(this);
}
}
public class Form2:Form{
private void button1_Click(object sender, EventArgs e)
{
Form1 fm = (Form1)this.Owner;
MessageBox.Show(fm.A);//讀Form1的A
fm.A=11;//寫Form1的A
}
}
當然也可以使用委托繼續(xù)傳值
4.重構(gòu)窗體構(gòu)造函數(shù),初始化的時候傳值,只適合初始化的適合,不夠方便
5.委托+事件的方法
下面代碼是一個點擊Form1 button 使Form2的button顯示Form1.textbox內(nèi)容
可以一次性傳很多值,步驟是在窗體A中聲明一個事件,B窗體中實現(xiàn)相同方法簽名的方法為事件賦值,B中回調(diào)該方法
Form1的代碼:
public partial class Form1 : Form{
public string B //獲取textbox1的text
{
get { return textBox1.Text; }
set
{
textBox1.Text = value;
}
}
public delegate void EventArgsaccept(object sender, acceptEventArgs e);//聲明一個事件簽名的委托
public static event EventArgsaccept accept;//相當于實例化一個事件
private void button1_Click(object sender, EventArgs e)
{
acceptEventArgs ae = new acceptEventArgs();
ae.b = B;
if (accept != null) {
accept(this,ae);
}
}
}
}
public class acceptEventArgs : EventArgs {//封裝EventArgs類,添加可傳遞的屬性
public string b { get; set; }
}
//------------------->>----------------------------------end code of form1-----------
form2的代碼,實現(xiàn)一個相同簽名的方法,如我們的accept的簽名是 方法名(object a,acceptEventArgs b);
public partial class Form2 : Form{
private void Form2_Load(object sender, EventArgs e)
{
Form1.accept += Form1_accept;//為form1的事件賦值,當form1執(zhí)行該事件的時候會執(zhí)行該方法
}
void Form1_accept(object sender,acceptEventArgs e) {//實現(xiàn)一個相同方法簽名的方法
this.button1.Text = e.b;
}
}
//------------------------>>---------------
具體的原理,我想因為委托是函數(shù)指針所以可以通過傳值能保存函數(shù)指針的位置?所以可以標記相應(yīng)的實例的,執(zhí)行其他實例的方法?
還沒看編譯原理,發(fā)表一下自己看法,不要誤導(dǎo)大眾
6.通過全局數(shù)據(jù)讀寫,適合登陸驗證
AppDomain.CurrentDomain.GetData("user");
希望本文所述對大家的C#程序設(shè)計有所幫助。
相關(guān)文章
C#如何將DataTable導(dǎo)出到Excel解決方案
由于公司項目中需要將系統(tǒng)內(nèi)用戶操作的所有日志進行轉(zhuǎn)存?zhèn)浞?,考慮到以后可能還需要還原,所以最后決定將日志數(shù)據(jù)備份到Excel中2012-11-11
C#如何使用Bogus創(chuàng)建模擬數(shù)據(jù)示例代碼
這篇文章主要給大家介紹了關(guān)于C#如何使用Bogus創(chuàng)建模擬數(shù)據(jù)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用C#具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04

