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

前端 未结 7 697
闹比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:57

    There is another solution possible, rather dirty one.

    Make IHomepageCarouselItem have "Construct" method which takes pageData as parameter and returns IHomepageCarouselItem.

    Then do this:

       T factoryDummy = new T();
       List carouselItems = new List();
    
       if (jewellerHomepages != null)
       {
            foreach (PageData pageData in jewellerHomepages)
            {
                T homepageMgmtCarouselItem = (T)factoryDummy.Construct(pageData);
                carouselItems.Add(homepageMgmtCarouselItem);
            }
       }
       return carouselItems;
    

提交回复
热议问题