gpt4 book ai didi

c# - 如何将类似的方法调用组合到委托(delegate)模式中?

转载 作者:行者123 更新时间:2023-11-30 15:48:18 25 4
gpt4 key购买 nike

我有三种方法:

public void Save<T>(T entity)
{
using (new Transaction())
{
Session.Save(entity);
}
}

public void Create<T>(T entity)
{
using (new Transaction())
{
Session.Create(entity);
}
}

public void Delete<T>(T entity)
{
using (new Transaction())
{
Session.Delete(entity);
}
}

如您所见,唯一不同的是 using block 中的方法调用。我怎样才能重写它,让它变成这样:

public void Save<T>(T entity)
{
TransactionWrapper(Session.Save(entity));
}

public void Create<T>(T entity)
{
TransactionWrapper(Session.Create(entity));
}

public void Save<T>(T entity)
{
TransactionWrapper(Session.Save(entity));
}

换句话说,我将方法调用作为参数传递,TransactionWrapper 方法围绕方法调用包装了一个事务。

最佳答案

你可以传递一个 Action<T>指定要执行的操作的方法:

private void ExecuteInTransaction<T>(Action<T> action, T entity)
{
using (new Transaction())
{
action(entity);
}
}

public void Save<T>(T entity)
{
ExecuteInTransaction(Session.Save, entity);
}

但在我看来,如果您的 ExecuteInTransaction 方法不是更复杂,那么这对您的原始代码来说没有什么值得改进的地方。

关于c# - 如何将类似的方法调用组合到委托(delegate)模式中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com