伊莉討論區

標題: (以解決)請問各位先進...C#是否有把"資料類型"導入函式的方法 [打印本頁]

作者: baepi    時間: 2018-1-22 11:10 AM     標題: (以解決)請問各位先進...C#是否有把"資料類型"導入函式的方法

本帖最後由 baepi 於 2018-1-23 04:12 PM 編輯

近來小弟開始初涉C#這領域
有個專案是全動態創建UI
過程並不難...創建元件 + 把該元件丟到指定的容器便能顯示(如下)
  1. Button bt = new Button();
  2.                 bt.SetBounds(10, 10, 100, 20);
  3. this.pictureBox1.Controls.Add(bt);
複製代碼
但如今有個糾結點...因為會有多個容器...(如: PictureBox   Panel  GroupBox )
若是創建個button...以我目前的寫法會變得極度冗長(如下)
  1. public void add_Button (int x , int y , int w , int h , object obj , int sw)
  2.         {
  3.             Button bt = new Button();
  4.             bt.SetBounds(x, y, w, h);
  5.             switch(sw)
  6.             {
  7.                 case 0:
  8.                     if(true)
  9.                     {
  10.                         PictureBox pb = (PictureBox)obj;
  11.                         pb.Controls.Add(bt);
  12.                     }
  13.                     break;
  14.                 case 1:
  15.                     if (true)
  16.                     {
  17.                         Panel p = (Panel)obj;
  18.                         p.Controls.Add(bt);
  19.                     }
  20.                     break;
  21.                 case 2:
  22.                     if (true)
  23.                     {
  24.                         GroupBox gb = (GroupBox)obj;
  25.                         gb.Controls.Add(bt);
  26.                     }
  27.                     break;
  28.             }
複製代碼
以上只是把我原本的程式簡化(因為容器太多了)...如此不僅不方便閱讀....以後若是有問題感覺也難以檢修(畢竟要創建的UI有很多很多
因此想請問....能否有辦法將函式優化成(如下)
使用者只要輸入add_Button (10 ,10 , 100 , 20 , this.pictureBox1 , PictureBox );
也即是(如上)...最後一個參數可導入資料類型...讓該函式可直接知道收到的obj是甚麼資料類型


作者: sggleeee    時間: 2018-1-22 09:17 PM

雖然不是很清楚您的需求......
我假設您是想動態增加元件(例如:Button)到對應的容器中(pictureBox1, groupBox1), 然後您希望透過傳遞一個參數來動態建立原件到參數所指定的容器中......

底下這段您看看有沒有符合需求:
  1. private void button1_Click(object sender, EventArgs e)
  2. {
  3.         AddControl(20, 20, 100, 20, pictureBox1);  //pictureBox1中加button
  4.         AddControl(20, 20, 100, 20, groupBox1);   //groupBox1中加button      
  5. }

  6. void AddControl(int x, int y, int w, int h, Control control)
  7. {
  8.         Button bt = new Button();
  9.         bt.SetBounds(x, y, w, h);           
  10.            
  11.         bt.Parent = control;                     
  12. }
複製代碼

作者: 羕漾    時間: 2018-1-23 12:32 AM

1. 大多數 UI 物件都會繼承 Control 這個類別,你只要以這個類別當參數,就能使用共用方法
2. 透過 typeof(obj) 或 obj.GetType().FullName 可以辯識其內容物為何,可以針對其內容物作轉型的動作,並使用該型別自己的方法。




歡迎光臨 伊莉討論區 (http://www48.eyny.com/) Powered by Discuz!