c# - 从使用方法作为参数的方法返回字符串

标签 c# asp.net

我有一个 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 被假定为无效。

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

最佳答案

你想要一个 Func<SqlConnection, string> . Action用于 void方法,Func对于返回某些东西的方法。

关于c# - 从使用方法作为参数的方法返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17727908/

相关文章:

c# - 什么更快 : expression trees or manually emitting IL

c# - Tizen.NET 调试错误无法加载文件或程序集'Samsung.Sap

c# - 包含数字 .ToString() 格式的 HTML

c# - 使用继承向内置类添加函数

c# - 向 ASP.NET MVC View 中的表动态添加列

c# - 对于包含 ASP.NET 项目的 .NET 框架解决方案,迁移到 "new project system"(PackageReference) 是否安全/可行?

c# - 轮数 .Net 中的下一个 0.25

c# - 如何从远程客户端机器传输到开发团队软件崩溃?

c# - 如何将逗号分隔的电子邮件列表与正则表达式匹配?

c# - 带参数的 AutoMapper 依赖注入(inject)