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

前端 未结 7 692
闹比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<T> carouselItems = new List<T>();
    
       if (jewellerHomepages != null)
       {
            foreach (PageData pageData in jewellerHomepages)
            {
                T homepageMgmtCarouselItem = (T)factoryDummy.Construct(pageData);
                carouselItems.Add(homepageMgmtCarouselItem);
            }
       }
       return carouselItems;
    
    0 讨论(0)
提交回复
热议问题