C# 实现泛型方法的正确方法

C# right way implement generic method

我有一些重复的代码。这与 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>()。在那个 generick 方法中,我不知道如何选择我需要设置的 bool 变量或我需要清除的 hashset 变量。 与其他重复方法相同。你能告诉我,我如何重构这段代码吗? 谢谢。

查看下面的代码:

class Attribute<T>
{
    public bool isRightValue;
    public HashSet<T> relatedHashSet;
    private T _value;

    public T GetValue(T3 somevalue)
    {
        return (somevalue != othervalue) || isRightValue ? _value : default(T);
    }

    public Clear()
    {
         isRightValue = true;
         relatedHashSet.Clear();
    }
}

class Foo
{
    public Attribute<T1> firstAttribute;
    public Attribute<T2> secondAttribute;
    ...

    public Foo()
    { ... }
    ...
}