繁体   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