2011-06-21 22 views
-1

我有一個方法類型在c#方法則params的

public string GetValue(TextBox txt, DropdownList ddl) 
{ 
    if(txt != null) 
     return txt.text; 
    else 
     return ddl.SelectedValue; 
} 

我只能通過其中文本框或ddI和空爲其他PARAM。我該如何解決這個問題? 我動態地調用該方法,並且一次存在TextBox或DDl。所以基於此我必須從那個控制返回值。

我收到一些錯誤消息,因爲當我傳遞Null時,Method有無效參數。

+5

你究竟想要完成什麼? –

+1

你想要做什麼? – DeveloperX

+0

因此,其中一個參數必須爲null,並且必須返回另一個的值,是嗎? –

回答

6

我只能傳遞文本框或ddl,其他參數爲null。我該如何解決這個問題?

如果這是您要強制執行的業務規則,則不會解決它,而是更改它。使用方法重載只能接受你實際想要使用的參數類型。

public string GetValue(TextBox tb) 
public string GetValue(DropDownList ddl) 
2

我不認爲你應該做這樣的方法。

從將價值txtMyText.Text;

,或者你有

var value = GetValue(null, ddlMyList); 

你有一個像

var value = GetValue(txtMyText, null); 

一些代碼簽名這臺價值ddl.SelectedValue;

這裏的問題這是否會消除可讀性。當我讀取你的代碼時,我發現你正在執行一個GetValue(),但我爲什麼在某些參數中傳入null時感到茫然。

它實際上是相當清楚,閱讀代碼時,只看到:

var value = txtMyTextBox.Text; 
var dropDownValue = ddlMyList.SelectedValue; 

使得這種方法是不是真的有用,因爲你必須處理每一個控制型。這些類已經有方法來獲得它們的價值,並且您試圖編寫一個實用程序方法,無論類類型如何,它都會得到一個值,從而掩蓋了真正發生的情況,而且價值很小。此外,如果向此方法添加更多類型,則最終將執行If/Else,直到找到類型並返回該值。這會導致不必要的CPU週期,特別是因爲你已經知道在設計時的類型(因爲你在空傳遞的一個參數。)如果你想傳遞很多參數可以使用關鍵字PARAM

1

public string GetValue(params object[] controls) 
{ 
    foreach (var item in controls) 
    { 
     if (item != null) 
     { 
      if (item is TextBox) 
       return (item as TextBox).Text; 
      if (item is CheckBox) 
       return (item as CheckBox).Checked.ToString(); 

      if (item is DropDownList) 
       return (item as DropDownList).SelectedValue.ToString(); 
     } 
    } 
    return string.Empty; 
} 

並調用該方法,因爲這

  GetValue(TextBox1); 
      GetValue(DropDownList1); 
GetValue(CheckBox1); 
     GetValue(null,DropDownList1); 
     GetValue(TextBox1,DropDownList1); 
    GetValue(TextBox1,DropDownList1,CheckBox1); 
0

每個控制繼承的類control。所以一個參數就足夠了。你只需要確定類型:

public string GetValue(Control ctl) { 
    if (ctl != null) { 

    //Textbox 
    if (ctl is TextBox) return ctl.Text; 
    //Combobox 
    if (ctl is ComboBox) { 
     ComboBox cb = ctl as ComboBox; 
     return cb.SelectedText; 
    } 
    //... 
    } 
    //Default Value (You can also throw an exception 
    return ""; 
}