我在名为 SqlInteraction 的类中有一个方法:
public static string sqlQueryReturnString(Func<SqlConnection, string> sqlMethod)
{
string result = "";
SqlConnection conn = new SqlConnection();
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
try
{
//open SQL connection
conn.Open();
result = sqlMethod(conn);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.ToString());
}
finally
{
conn.Close();
}
return result;
}
这是使用它的不同类中的另一个方法:
private string getPKofUserLoggedIn(SqlConnection conn, string PointPerson)
{
int result = 0;
SqlCommand getPKofUserLoggedIn = new SqlCommand("SELECT [PK_User] FROM [User] WHERE [LoginName] = @userIdParam", conn);
//create and assign parameters
getPKofUserLoggedIn.Parameters.AddWithValue("@userIdParam", PointPerson);
//execute command and retrieve primary key from the above insert and assign to variable
result = (int)getPKofUserLoggedIn.ExecuteScalar();
return result.ToString();
}
我在第二种方法中传递字符串时遇到问题。如果我删除“string PointPerson”,则此调用有效:
SqlInteraction.sqlQueryReturnString(getPKofUserLoggedIn);
如何传递字符串?
最佳答案
Func<SqlConnection, string>
读作“一个接受 SqlConnection
的函数”参数并返回 string
' - 如果您删除 PointPerson,那么您就拥有了。
如果要从外部方法添加参数,可以执行以下操作:
var myParam = "some string";
SqlInteraction.sqlQueryReturnString(conn => getPKofUserLoggedIn(conn, myParam));
关于c# - 在以方法作为参数的方法中传递字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19817537/