C# generics problem - newing up the generic type with parameters in the constructor

前端 未结 7 743
闹比i
闹比i 2020-12-09 04:02

I am trying to create a generic class which new\'s up an instance of the generic type. As follows:

public class HomepageCarousel : List
            


        
7条回答
  •  感动是毒
    2020-12-09 04:38

    Jared's answer is still a good way to go - you just need to make the constructor take the Func and stash it for later:

    public class HomepageCarousel : List where T: IHomepageCarouselItem
    {
        private readonly Func factory;
    
        public HomepageCarousel(Func factory)
        {
            this.factory = factory;
        }
    
        private List GetInitialCarouselData()
        {
           List carouselItems = new List();
    
           if (jewellerHomepages != null)
           {
                foreach (PageData pageData in jewellerHomepages)
                {
                    T homepageMgmtCarouselItem = factory(pageData);
                    carouselItems.Add(homepageMgmtCarouselItem);
                }
           }
           return carouselItems;
        }
    

    Then you just pass the function into the constructor where you create the new instance of the HomepageCarousel.

    (I'd recommend composition instead of inheritance, btw... deriving from List is almost always the wrong way to go.)

提交回复
热议问题