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

本文关键字:方法 实现 泛型方法 | 更新日期: 2024-06-14 08:23:22

我有一些重复的代码。这与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-变量或需要清除哪个hashset。与其他重复方法相同。你能告诉我如何重构这些代码吗?谢谢

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

请参阅下面的代码:

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()
    { ... }
    ...
}