How can I write a generic container class that implements a given interface in C#?

后端 未结 7 1721
太阳男子
太阳男子 2020-12-02 16:17

Context: .NET 3.5, VS2008. I\'m not sure about the title of this question, so feel free to comment about the title, too :-)

Here\'s the scenario: I have several cla

相关标签:
7条回答
  • 2020-12-02 16:45

    You could subclass List<T> or some other collection class and use the where generic type constraint to limit the T type to be only IStartable classes.

    class StartableList<T> : List<T>, IStartable where T : IStartable
    {
        public StartableList(IEnumerable<T> arr)
            : base(arr)
        {
        }
    
        public void Start()
        {
            foreach (IStartable s in this)
            {
                s.Start();
            }
        }
    
        public void Stop()
        {
            foreach (IStartable s in this)
            {
                s.Stop();
            }
        }
    }
    

    You could also declare the class like this if you didn't want it to be a generic class requiring a type parameter.

    public class StartableList : List<IStartable>, IStartable
    { ... }
    

    Your sample usage code would then look something like this:

    var arr = new IStartable[] { new Foo(), new Bar("wow") };
    var mygroup = new StartableList<IStartable>(arr);
    mygroup.Start(); // --> calls Foo's Start and Bar's Start
    
    0 讨论(0)
提交回复
热议问题