2012-03-22 63 views
1

只需學習C#,單選按鈕和複選框。沒有緊迫感。 該代碼用於顯示檢查控件的名稱,但它似乎不是一個優雅的解決方案。更好的解決gui的代碼?

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace TVC 
{ 
    public partial class Form1 : Form 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     private void button1_Click(object sender, EventArgs e) 
     { 
      label1.Text = "you clicked" + compute(); 
     } 


     string compute() 
     { 
      string result = ""; 
      object o=label1; 

      while (((Control)o).TabIndex!=7) 
      { 
       if ((o is RadioButton)||(o is CheckBox)) 
       { 

        if ((o is RadioButton)&&((RadioButton)o).Checked) 

        result += " "+((RadioButton)o).Text; 

        if ((o is CheckBox)&&((CheckBox)o).Checked) 

        result += " "+((CheckBox)o).Text; 

       } 

       o = GetNextControl((Control)o, true); 
      } 



      return result; 
     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 

     } 
    } 
} 

的checboxes和單選按鈕tabindexes從-1至6計數,標記爲0,按鈕7,使得GetNextControl工作。有更好的代碼可以工作嗎? enter image description here

+3

無論你做什麼,總是避免幻數。即使這是最後的代碼,將這個'7'提取到一個單獨的常量。 – rid 2012-03-22 04:16:12

+0

+1對於魔術數字 – 2012-03-22 04:18:53

回答

1

我剛剛測試過這個並驗證它的工作原理。它使用遞歸和更新的dynamic關鍵字,因爲它似乎RadioButtonCheckBox繼承自ButtonBase,它不具有Checked屬性,否則可以將其轉換爲該屬性。動態允許我避免,因爲我已經知道控件類型。

private void button1_Click(object sender, EventArgs e) 
    { 
     label1.Text = compute(this.Controls); 
    } 
    private string compute(Control.ControlCollection controls) 
    { 
     string result = String.Empty; 
     foreach (Control control in controls) 
     { 
      if (control.Controls != null) 
       result += compute(control.Controls); 
      if (control is RadioButton || control is CheckBox) 
      { 
       dynamic checkControl = control; 
       if (checkControl.Checked) 
       { 
        result += checkControl.Text + ";"; 
       } 
      } 
     } 
     return result; 
    } 
+0

的一個很好的建議謝謝,我不知道ControlCollection或動態 – steelponey 2012-03-22 05:41:09

1

如果你發現自己使用isas關鍵字來控制分支,有你沒有利用polymorphism一個很好的機會。

如果你想擁有可以根據程序中的邏輯顯示自己狀態的控件,一種更簡潔的方法是對每個控件進行子類化並覆蓋ToString()

將在控制創建文本表示,而不是在使用多個控件的代碼邏輯(多麼複雜將您的分支邏輯得到,如果你添加了10個新的控件類型?)

最後,我想使用foreach而不是while與一個硬編碼的數字遍歷控件。