我有两个相同的方法,但其中一个在 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/