简体   繁体   中英

C#: Subclass List<Something>?

I have a class EqualCondition which implements my own interface ICondition , which has only one method: SatisfiedBy(Something) .

public class EqualCondition : ICondition {
    private Something m_Something;

    public HelloCondition(Something something) {
        m_Something = something;
    }

    // Magic!!!
    public bool SatisfiedBy(Something something) {
        return something == m_Something;
    }
}

So ICondition is very simple to implement. Now I'm trying to create a CombinationCondition which also implements it. The idea is that CombinationCondition which will contain a list of ICondition s which will determine whether SatisfiedBy will be successful or not.

My first thought was to make CombinationCondition implement IList<Something> but I quickly realized that I was only duplicating List<Something> . So why not just subclass it?

That idea sounded fine until I started thinking again about how to implement SatisfiedBy if I just subclassed List<Something> . I need to do:

return innerList.All(x => x.SatisfiedBy(something))

But how do I access the inner list?

Personally, for the use case you're showing, I would just make this implement IEnumerable<Condition> . You could then just implement the GetEnumerator by calling the (internal, encapsulated) List<Condition> 's method.

Potentially, ICollection<Condition> may make more sense (so you can add conditions at runtime), but only if you need that capability. Implementing IList<T> seems like overkill in this situation, for the use cases I'd see with this.

From what you have posted, I would just have CombinationCondition contain (encapsulate) a List<Something> . No need for the outside world to know it is a list unless absolutely necessary.

Edit 1:

public class CombinationCondition : ICondition {
private List<ICondition> list;

public CombinationCondition(List<ICondition> list) {
    this.list = list;
}

// if you need it
public void AddCondition( ICondition condition ){
    list.Add( condition );
}

// Still Magic!!!
public bool SatisfiedBy(Something something) {
    return list.Any( x => x.SatisfiedBy( something ) );
}

}

Edit 2:
You might also consider renaming CombinationCondition to CompoundCondition ...makes more sense, at least to me :)

I'm not sure I 100% understand what you are trying to do, but would this solve your need?

public interface ICondition<T>
{
   bool SatisfiedBy(T something);
}

That way, you can just implement it for any generic type you need

One possibility would be a property of type IList<ICondition> called maybe "Conditions".

You don't need to access the inner list - you could access your class "itself".

However, prefer sublassing from ICollection<T>.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM