使用SqlConnection转换为Func委托 [英] Converting using SqlConnection to Func delegate

查看:180
本文介绍了使用SqlConnection转换为Func委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码被复制并粘贴在多个地方。唯一的区别是在使用中间有一个单一的调用,这些更改。所以我做了一个

I have the following code that is being copied and pasted in a number of places. The only difference being that there is a single call in the middle of the usings which changes. So I made a

public MyEntity Read(int id)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return MyDataLayer.Select(sqlConn, id);
    }
}

所以我想出了这个。但是,我的问题是如何将sqlConn var传递给调用?

So I came up with this. However, my problem is how do i pass the sqlConn var to the call?

public TResult UsingSqlConnection<TResult>(Func<TResult> myFunction)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return myFunction();
    }
}

public MyEntity Read(int id)
{
    return UsingSqlConnection(() => MyDataLayer.Read(id)); 
   //PROBLEM: Read() requires sqlConn
}

我的头 - 它看起来不是将其作为参数传递,我需要在MyDataLayer中为SqlConn创建一个属性,并使用接口在UsingSqlConnection方法中分配它。虽然我不排除这个重构,但我想知道我是否缺少某些东西,因为这是我以这种方式第一次使用Func代表。

Off the top of my head - it looks like instead of passing it as a param, that I need to create a property for SqlConn in MyDataLayer and assign it in the UsingSqlConnection method using an interface. While i wont rule out that refactor, I am wondering if I am missing something as this is my first attempt with Func delegates in this way.

推荐答案

Func 可以有参数:

public TResult UsingSqlConnection<TResult>(Func<SqlConnection, TResult> myFunc)
{
    using (SqlConnection sqlConn = new SqlConnection(ConnectionString))
    {
        sqlConn.Open();
        return myFunc(sqlConn);
    }
}

public MyEntity Read(int id)
{
    return UsingSqlConnection((sqlConn) => MyDataLayer.Read(sqlConn, id));       
}

这篇关于使用SqlConnection转换为Func委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆