c# - 如何避免两种方法中的代码重复?

标签 c#

我有两个相同的方法,但其中一个在 try catch 中有 return 语句

public void A(Guid agentId)
{
     var agent = _agentsProvider.GetAgentById(agentId);
     var updateCompletionSource = C(agentId);
     try
     {
         var cacheEntry = UpdateAgentMetadataCacheEntry(agent, true, false);
         updateCompletionSource.SetResult(cacheEntry);
     }
     catch (Exception e)
     {
         updateCompletionSource.SetException(e);
     }
}

private Entry B(IAgent agent)
{
     var updateCompletionSource = C(agent.Id);
     try
     {
          var cacheEntry = UpdateAgentMetadataCacheEntry(agent, false, false);
          updateCompletionSource.SetResult(cacheEntry);
          return cacheEntry;
      }
      catch (Exception e)
      {
          updateCompletionSource.SetException(e);
          return GetPreviousCacheEntry();
      }
}

如何收集相同的部分并用这个部分创建新的方法?

最佳答案

除非 GetPreviousCacheEntry 可能产生有问题的副作用,否则在我看来您根本不需要方法 A

如果您对它不感兴趣,只需调用方法 B 并忽略返回值。

如评论中所述,方法除了返回语句之外 - 因为它们为 UpdateAgentMetadataCacheEntry 使用不同的第二个参数,并且它们具有不同的参数也一样(一个有一个 Guid,一个有一个 Agent)。您可以将其重构为:

private Entry B(IAgent agent, bool foo)
{
     var updateCompletionSource = C(agent.Id);
     try
     {
          var cacheEntry = UpdateAgentMetadataCacheEntry(agent, foo, false);
          updateCompletionSource.SetResult(cacheEntry);
          return cacheEntry;
      }
      catch (Exception e)
      {
          updateCompletionSource.SetException(e);
          return GetPreviousCacheEntry();
      }
}

...显然,foo 有一个有意义的名称。我假设参数类型的差异在现实中不是问题。

关于c# - 如何避免两种方法中的代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34749815/

相关文章:

c# - 在 REST 服务中反序列化 JSON

将 excel 与 oledb 结合使用时出现 C# 异常 : External table is not in the expected format.

c# - 无法在 ASP.NET C# 中转换字符

C# 定时器和网络调用并行

c# - 在 .NET .config 文件中读取和写入值

c# - Bootstrap 4 Carousel 在 Blazor(预览版 7)服务器端不工作

c# - 我怎样才能使 dll.config 成为 Nuget 包的一部分

c# - 如何仅使用 2 replace 替换完全匹配的字符串

c# - 修改程序中的实际代码

c# - 一种解析带有 'Flags' 的 .NET 枚举字符串或 int 值的方法