string.compare和字符串进行比较

Sri*_*ava 1 c# visual-studio winforms

我有这样的代码

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();
            }
        }
Run Code Online (Sandbox Code Playgroud)

但是这里使用(字符串)会出现区分大小写的问题.所以我想使用string.comapare代替(string).

任何人都可以给我任何提示如何使用它.

Jon*_*eet 5

我建议你使用:

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

if (selectedItem.Equals("NonPrimaryKeyTables",
                        StringComparison.CurrentCultureIgnoreCase))
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

选择正确的字符串比较可能很棘手.有关更多信息,请参阅此MSDN文章.

不会Compare像其他人建议的那样建议使用,仅仅是因为它不是正确的重点 - Compare旨在用于测试哪些订单字符串在排序时应该出现.这有允许你测试平等的副产品,但这不是主要目标.使用Equals显示所有你关心的是相等 - 如果两个字符串不相等,你不关心哪个会先出现.使用Compare工作,但它不会让你的代码尽可能清楚地表达自己.