【问题标题】:C# right way implement generic methodC#正确方法实现泛型方法
【发布时间】: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&lt;TYPE&gt;()。在那个通用方法中,我不知道如何选择我需要设置哪个bool-variable 或者我需要清除哪个hashset。 与其他重复方法相同。你能告诉我,我如何重构这段代码? 谢谢。

【问题讨论】:

    标签: c# generics coding-style refactoring dry


    【解决方案1】:

    见下面的代码:

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

    【讨论】:

    • 如果我想按请求类型返回属性,我应该如何实现方法? public Attribute&lt;T&gt; GetAttribute(T){ // what should be there? }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2021-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多