C#窗体传值

整理一下:

1.静态变量传值,非常简单适合简单的非实例的

public calss form1:Form{
    public static int A;
}
public class form2:Form{
   form1.A=1; 
}

2.委托传值

public class form1:Form{
  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变量设置为10
  form1 fm1=new form1();
  fm1.setIntADel(12);//通过实例的委托将新实例fm1的A变量设置为12
  }
}

3.使用onwer属性,适合对话框之间的传值

public class Form1:Form{
  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         
           
            
        }
}

  当然也可以使用委托继续传值

4.重构窗体构造函数,初始化的时候传值,只适合初始化的适合,不够方便

5.委托+事件的方法

下面代码是一个点击Form1 button 使Form2的button显示Form1.textbox内容
可以一次性传很多值,步骤是在窗体A中声明一个事件,B窗体中实现相同方法签名的方法为事件赋值,B中回调该方法
Form1的代码:
//--------------------------------------->>--------------------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的代码,实现一个相同签名的方法,如我们的accept的签名是 方法名(object a,acceptEventArgs b);
//-------------------------------------->>---------------------------------------code of form2---
 public partial class Form2 : Form{
  private void Form2_Load(object sender, EventArgs e)
        {
            Form1.accept += Form1_accept;//为form1的事件赋值,当form1执行该事件的时候会执行该方法
        }
  void Form1_accept(object sender,acceptEventArgs e) {//实现一个相同方法签名的方法
            this.button1.Text = e.b;            
     }
}
//------------------------>>---------------

  

具体的原理,我想因为委托是函数指针所以可以通过传值能保存函数指针的位置?所以可以标记相应的实例的,执行其他实例的方法?

还没看编译原理,发表一下自己看法,不要误导大众

6.通过全局数据读写,适合登陆验证

 AppDomain.CurrentDomain.SetData("user", "小明");
 AppDomain.CurrentDomain.GetData("user");

  

原文地址:https://www.cnblogs.com/keithmoring/p/4075623.html