2011-11-11 131 views

回答

61

你的静态方法应该从:

public static class SimpleUsing 
{ 
    public static void DoUsing(Action<MyDataContext> action) 
    { 
     using (MyDataContext db = new MyDataContext()) 
      action(db); 
    } 
} 

要:

public static class SimpleUsing 
{ 
    public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action) 
    { 
     using (MyDataContext db = new MyDataContext()) 
      return action(db); 
    } 
} 

这个答案脱胎于的意见,所以我可以提供代码。有关完整的阐述,请参阅下面的@ sll的答案。

84

您可以使用Func<T, TResult>泛型委托。 (见MSDN

Func<MyType, ReturnType> func = (db) => { return new MyTytpe(); } 

也有其考虑返回值有用泛型委托:

  • Converter<TInput, TOutput>MSDN
  • Predicate<TInput> - 总是返回布尔(MSDN

方法:

public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory) 

泛型委托

Func<InputArgumentType, MyType> createInstance = db => return new MyType(); 

执行:

MyType myTypeInstance = SimpleUsing.DoUsing(
          createInstance(new InputArgumentType())); 

或明确:

MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType()); 
+0

对 - 你能提供一个这个方法应该是什么样子的例子吗? – 4thSpace

+0

我sitll不遵循如何适合英寸可以显示它的方法签名(即公共静态无效DoUsing(动作行动))? @ L.B:是的 - 我的文章是结果。 – 4thSpace

+3

@ L.B--要求人们对谷歌没有建设性。 SO存在以提供完整的答案。 –

11

您还可以利用lambda或匿名方法可以关闭其封闭范围中的变量的事实。

MyType result; 

SimpleUsing.DoUsing(db => 
{ 
    result = db.SomeQuery(); //whatever returns the MyType result 
}); 

//do something with result 
+0

是的,这就是所谓的Closure(功能语言的东西,它也适用于我们) – sll