将DataContext传递给Action()

时间:2011-11-11 19:30:31

标签: c# .net linq

而不是:

 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?

1 个答案:

答案 0 :(得分:7)

泛型类型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
});