2010-11-30 173 views
1

我有這樣的代碼string.compare和字符串比較

private void btnStartAnalysis_Click(object sender, EventArgs e) 

      { 

     //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions. 
     if((string) (cmbOperations.SelectedItem) == "PrimaryKeyTables") 
      { 
      //This is the function call for the primary key checking in DB 
      GetPrimaryKeyTable(); 
      } 

     //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions. 
     if((string) (cmbOperations.SelectedItem) == "NonPrimaryKeyTables") 
      { 
      //This is the function call for the nonPrimary key checking in DB 
      GetNonPrimaryKeyTables(); 
      } 

     //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions. 
     if((string) (cmbOperations.SelectedItem) == "ForeignKeyTables") 
      { 
      //This is the function call for the nonPrimary key checking in DB 
      GetForeignKeyTables(); 
      } 

     //Checks for the selectedItem in the cmbOpearions dropdown and make call to appropriate functions. 
     if((string) (cmbOperations.SelectedItem) == "NonForeignKeyTables") 
      { 
      //This is the function call for the nonPrimary key checking in DB 
      GetNonForeignKeyTables(); 
      } 

     if((string) (cmbOperations.SelectedItem) == "UPPERCASEDTables") 
      { 
      //This is the function call for the nonPrimary key checking in DB 
      GetTablesWithUpperCaseName(); 
      } 

     if((string) (cmbOperations.SelectedItem) == "lowercasedtables") 
      { 
      //This is the function call for the nonPrimary key checking in DB 
      GetTablesWithLowerCaseName(); 
      } 
     } 

但這裏使用(串),使問題的情況下,sensitiveness.So我要到位(串)的使用string.comapare。

任何人都可以給我任何提示如何使用它。

回答

1

試試這個:

if (string.Compare((string) cmbOperations.SelectedItem, 
     "NonForeignKeyTables", true) == 0) // 0 result means same 
    GetNonForeignKeyTables(); 
0

MSDN有關於string.compare方法真的很好的解釋.. 你只需要編寫

String.Compare (String, String) 

來比較你的字符串..用開關指令的情況下使用這將是確定..

使用

String.Compare (String, String, boolean) 

要設置的情況下comparaison

+0

查看我的答案,爲什麼我不會使用`Compare`。另外還不清楚switch/case如何與此相關。 – 2010-11-30 07:58:07

0

對於區分大小寫的比較:

string a = "text1"; 
    string b = "TeXt1"; 

    if(string.Compare(a, b, true) == 0) { 
     Console.WriteLine("Equal"); 
    } 
5

我建議你使用:

// There's no point in casting it in every if statement 
string selectedItem = (string) cmbOperations.SelectedItem; 

if (selectedItem.Equals("NonPrimaryKeyTables", 
         StringComparison.CurrentCultureIgnoreCase)) 
{ 
    ... 
} 

選擇正確的字符串比較可能會非常棘手。有關更多信息,請參閱此MSDN article

使用Compare其他人建議,只是因爲這是不正確的重點將不會建議 - Compare被設計用於何種順序字符串應該出現時,他們分類測試。這有副產品允許你測試平等,但這不是主要目標。使用Equals表明你所關心的只是平等 - 如果兩個字符串不相等,你不關心哪一個會先來。使用Compare工作,但它不會讓您的代碼儘可能清楚地表達自己。