关于将DataContext传递到Action()的问题的答案,如何从action(db)返回值?
SimpleUsing.DoUsing(db => {
// do whatever with db
});
应该更像:
MyType myType = SimpleUsing.DoUsing<MyType>(db => {
// do whatever with db. query buit using db returns MyType.
});
关于将DataContext传递到Action()的问题的答案,如何从action(db)返回值?
SimpleUsing.DoUsing(db => {
// do whatever with db
});
应该更像:
MyType myType = SimpleUsing.DoUsing<MyType>(db => {
// do whatever with db. query buit using db returns MyType.
});
Answers:
您的静态方法应来自:
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答案。
您可以使用Func<T, TResult>
通用委托。(请参阅MSDN)
Func<MyType, ReturnType> func = (db) => { return new MyType(); }
还有一些有用的泛型委托考虑了返回值:
方法:
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());