将DataContext传递到Action() [英] Passing DataContext into Action()

查看:79
本文介绍了将DataContext传递到Action()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代替:

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

我想使用一个Action()

I'd like to use an 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?

The main issue is how do I access the "db" variable to make use of the DataContext?

推荐答案

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

The generic types Action<T1>, Action<T1, T2>, etc. define a delegate which takes some arguments. So you can write it like this:

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
});

这篇关于将DataContext传递到Action()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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