C#: Generic types that have a constructor?

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

    It can be done with reflection:

    public void CreateItem()
    {
      int constructorparm1 = 10;
      T oItem = Activator.CreateInstance(typeof(T), constructorparm1) as T;
    }
    

    But there is no generic constraint to ensure that T implements the desired constructor, so I wouldn't advise doing this unless you are careful to declare that constructor in every type that implements the interface.

提交回复
热议问题