【问题标题】:Return a string from a method that uses a method as a parameter从使用方法作为参数的方法返回字符串
【发布时间】:2013-07-18 15:35:26
【问题描述】:

我有一个想要返回字符串的 SQL 模板方法,以及执行我想要从中获取字符串的查询的各种方法:

private string sqlQueryReturnString(Action<SqlConnection> 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;
}

//Get the primary key of the currently logged in user
private string getPKofUserLoggedIn(SqlConnection conn)
{
    int result = 0;
    SqlCommand getPKofUserLoggedIn = new SqlCommand("SELECT [PK_User] FROM [User] WHERE [LoginName] = @userIdParam", conn);
    //create and assign parameters
    getPKofUserLoggedIn.Parameters.AddWithValue("@userIdParam", User.Identity.Name);
    //execute command and retrieve primary key from the above insert and assign to variable
    result = (int)getPKofUserLoggedIn.ExecuteScalar();
    return result.ToString();
}

以上是我认为的处理方式。这将是电话:

string test = sqlQueryReturnString(getPKofUserLoggedIn);

这部分不起作用:

result = sqlMethod(conn);

似乎 sqlMethod 被假定为无效。

我该怎么做才能获得我想要的功能?

【问题讨论】:

  • 你想要什么功能?你想让 sqlMethod 返回字符串吗?然后你应该把它改成返回字符串

标签: c# asp.net


【解决方案1】:

你想要一个Func&lt;SqlConnection, string&gt;Action 用于 void 方法,Func 用于返回某些内容的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-26
    • 2021-04-19
    • 1970-01-01
    • 2016-05-19
    • 1970-01-01
    • 2012-06-25
    • 2022-01-23
    • 1970-01-01
    相关资源
    最近更新 更多