C#: Generic types that have a constructor?

后端 未结 5 1364
一个人的身影
一个人的身影 2021-02-02 12:28

I have the following C# test code:

  class MyItem
  {
    MyItem( int a ) {}
  }

  class MyContainer< T >
    where T : MyItem, new()
  {
    public void          


        
5条回答
  •  鱼传尺愫
    2021-02-02 13:10

    One pattern I use is to have the constrained class implement an interface which defines an Init method with the appropriate signature:

    interface IMyItem
    {
        void Init(int a);
    }
    
    class MyItem : IMyItem
    {
        MyItem() {}
        void Init(int a) { }
    }    
    
    class MyContainer< T >
        where T : MyItem, IMyItem, new()
    {
        public void CreateItem()
        {
            T oItem = new T();
            oItem.Init( 10 );
        }
    }
    

提交回复
热议问题