将DataContext传递给Action()

本文关键字:Action DataContext | 更新日期: 2023-09-27 18:14:34

而不是:

 using(MyDataContext db = new MyDataContext())
 {
   //do something
 }

我想使用Action()

public static class SimpleUsing
{
  public static void DoUsing(Action action)
  {
    using(MyDataContext db = new MyDataContext())
    {
      //do something
    }
  }
}

将用作

SimpleUsing.DoUsing(() =>
{
   //but how to get DataContext variable?
}

主要问题是我如何访问"db"变量来利用数据上下文?

将DataContext传递给Action()

泛型Action<T1>, Action<T1, T2>等定义了一个接受一些参数的委托。所以你可以这样写:

public static class SimpleUsing
{
    public static void DoUsing(Action<MyDataContext> action)
    {
        using (MyDataContext db = new MyDataContext())
           action(db);
    }
    public static T DoUsing(Func<MyDataContext, T> fn)
    {
        using (MyDataContext db = new MyDataContext())
           return fn(db);
    }
}
// ...
SimpleUsing.DoUsing(db => {
    // do whatever with db
});
var result = SimpleUsing.DoUsing(db => {
    return 42; // uses Func overload, result will be 42
});