【发布时间】:2016-04-04 15:39:48
【问题描述】:
我有一些重复的代码。这与 DRY 原则相矛盾。但我不知道如何用泛型方法替换它。
class Foo
{
public bool isFirstAttribHasRightValue;
public bool isSecondAttribHasRightValue;
private readonly T1 _firstAttrib;
private readonly T2 _secondAttrib;
public HashSet<T1> relatedToFirstAttrib;
public HashSet<T2> relatedToSecondAttrib;
...
public C()
{ ... }
public T1 GetFirstAttrib(T3 somevalue)
{
return (somevalue != othervalue) || isFirstAttribHasRightValue ? _firstAttrib : default(T1);
}
public T2 GetSecondAttrib(T3 somevalue)
{
return (somevalue != othervalue) || isSecondAttribHasRightValue ? _secondAttrib : default(T2);
}
public ClearRelatedToFirst()
{
isFirstAttribHasRightValue = true;
relatedToFirstAttrib.Clear();
}
public ClearRelatedToSecond()
{
isSecondAttribHasRightValue = true;
relatedToSecondAttrib.Clear();
}
...
}
我喜欢将重复的方法(例如 ClearRelatedToFirst() 和 ClearRelatedToSecond())替换为 ClearRelatedToAttrib<TYPE>()。在那个通用方法中,我不知道如何选择我需要设置哪个bool-variable 或者我需要清除哪个hashset。
与其他重复方法相同。你能告诉我,我如何重构这段代码?
谢谢。
【问题讨论】:
标签: c# generics coding-style refactoring dry