我有这样的代码
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();
}
}
但是这里使用(字符串)会在区分大小写的情况下产生问题。所以我想使用string.comapare代替(字符串)。
任何人都可以给我任何提示如何使用它。
答案 0 :(得分: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
会工作,但它不会让您的代码尽可能清晰地表达自己。
答案 1 :(得分:1)
试试这个:
if (string.Compare((string) cmbOperations.SelectedItem,
"NonForeignKeyTables", true) == 0) // 0 result means same
GetNonForeignKeyTables();
答案 2 :(得分:0)
MSDN对string.compare方法有很好的解释。 你只需要写
String.Compare (String, String)
比较你的字符串..用于Switch-case指令就可以了..
使用
String.Compare (String, String, boolean)
设置案例比较
答案 3 :(得分:0)
对于不区分大小写的比较:
string a = "text1";
string b = "TeXt1";
if(string.Compare( a, b, true ) == 0) {
Console.WriteLine("Equal");
}