簡體   English   中英

帶參數的C#方法

[英]C# method with parameters

我編寫了一些代碼來檢查給定的使用者名稱是否存在於我的SQL數據庫中。 請看下面:

string exists = String.Empty;
using (SqlConnection connection = new SqlConnection(connectionString))
{
   connection.Open();
   using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection))
   {
     using (SqlDataReader reader = command.ExecuteReader())
      {
            while (reader.Read())
            {
                for (int j = 0; j < reader.FieldCount; j++)
                 {
                       exists = reader.GetValue(j) + "";
                 }
            }
      }
   }
}

注意:在我的程序中已經聲明了connectionString

我正在幾種方法中使用此代碼,並且不想有重復的代碼,因此我正在考慮將其變成一種方法。

問題出在我使用上述代碼的方法中的下一段代碼使用了exists字符串,並檢查它是否為空。

偽代碼如下:

if(String.ISNullOrEmpty(exists))
{
//do some code
}
else
{
//do some code
}

我做了如下的方法:

private static string SubjectExistsChecker(string input, string exists)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection))
                {
                    using (SqlDataReader reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            for (int j = 0; j < reader.FieldCount; j++)
                            {
                                exists = reader.GetValue(j) + "";
                            }
                        }
                    }
                }
                return exists;
            }
        }

然后,我按如下方式調用該方法:

MethodName()
{
//some code asking for subjectName which we call `input`

 String exists = string.Empty;
 SubjectExistsChecker(input, exists);


 if (string.IsNullOrEmpty(exists))
{
//do some code
}
else
{
//do some code
}

如頂部所示,完全寫出代碼(不使用方法)時,此方法有效。

現在,我所做的方法,這是行不通的,並exists撐空。

有人可以幫忙嗎? 我要去哪里錯了? 我猜想它與exists字符串有關。

首先,由於SQL注入安全性問題,直接連接SQL字符串是一種不好的做法。

您可以並且應該使用參數化查詢,並在參數中設置值。

此處的示例: https : //docs.microsoft.com/zh-cn/dotnet/api/system.data.sqlclient.sqlcommand.parameters?view=netframework-4.7.2

其次。 你是不是分配串到你的exists的范圍的變量之外SubjectExistsChecker方法。 字符串是不可變的。

這應該適合您的情況:

 String exists = string.Empty;
 exists = SubjectExistsChecker(input, exists);

因為您使用的是String盡管它們是引用類型,但它們的本質是不可變的

您將需要返回字符串並將其分配回您的變量:

String exists = string.Empty;
exists = SubjectExistsChecker(input, exists);

並且看起來像是一條記錄,如果是,則無需執行while循環。

您未設置返回值:

添加:

exists = SubjectExistsChecker(input, exists);

問題在於您沒有使用在SubjectExistsChecker()計算出的值。 為了使用從方法中return ,可以對方法的調用進行賦值,如下所示:

String exists = SubjectExistsChecker(input, exists);

但是,如果采用這種方式,我們實際上並不需要將其作為方法的參數來提供-因為如果您查看它,則沒有任何東西依賴於此參數。 還要注意,我們傾向於用動詞來命名方法-因為它反映了它們的性質。 例如,您的方法可以命名為DoesSubjectExist 因此,您可以像這樣調整方法:

private static string DoesSubjectExist(string input)
{
    string exists = "";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection))
        {
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                {
                    for (int j = 0; j < reader.FieldCount; j++)
                    {
                        exists = reader.GetValue(j) + "";
                    }
                }
            }
        }
        return exists;
    }
} 

但是仍然不清楚您希望此方法的結果是什么? 我們可以從名稱中猜出什么,我們想檢查一個主題是否存在-我們不必知道它是什么。 在這種情況下,如果存在具有給定名稱的主題,則該方法返回true否則返回false 因此,需要進一步調整:

private static bool DoesSubjectExist(string input)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        // Note that query will probably need to be changed too for a more optimal solution.
        using (SqlCommand command = new SqlCommand("SELECT Subject_Name FROM Subject WHERE Subject_Name ='" + input + "'", connection)) 
        {
            using (SqlDataReader reader = command.ExecuteReader())
            {
                // Do we need this loop?
                while (reader.Read())
                {
                    // There is at least one match - so the subject exists.
                    if (reader.FieldCount > 0) return true;
                }
            }
        }
        return false; // If we get here, we didn't find anything.
    }
}  

因此,這將更具表現力。 注意您的用例:

MethodName()
{
    //some code asking for subjectName which we call `input`

    if (DoesSubjectExist(input))
    {
        //do some code
    }
    else
    {
        //do some code
    }
}

另外,請采納其他人的建議,以某種方式抽象您的SQL數據訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM