C#: Generic types that have a constructor?

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

    C#, and VB.Net for that matter, do not support the notion of constraining a generic to have a constructor with specific parameters. It only supports constraining to have an empty constructor.

    One work around is to have the caller pass in a factory lambda to create the value. For instance

    public void CreateItem(Func del) {
      T oItem = del(10);
    }
    

    Call site

    CreateItem(x => new SomeClass(x));
    

提交回复
热议问题