C#: Generic types that have a constructor?

后端 未结 5 1374
一个人的身影
一个人的身影 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:11

    There's no such generic constraint, so it's not possible directly (this is a CLR limitation). If you want this, you have to provide a factory class (which has a parameterless constructor), and pass it as a second generic type parameter.

提交回复
热议问题