Cannot create an instance of the variable type 'Item' because it does not have the new() constraint

后端 未结 3 1955
北恋
北恋 2020-12-24 05:08

I am trying to test a method - and getting an error:

Cannot create an instance of the variable type \'Item\' because it does not have the new() constr

3条回答
  •  攒了一身酷
    2020-12-24 05:25

    The Item in the line:

    Item i = new Item(p, 10);
    

    refers to the generic type parameter Item of the CountTestHelper method, not the class Item. Change the generic parameter name e.g.

    public void CountTestHelper() where TItem : IHasRect
    {
        Rectangle rectangle = new Rectangle(0, 0, 100, 100); 
        SomeClass target = new SomeClass(rectangle);            
        Point p = new Point(10,10);
        Item i = new Item(p, 10);    
        ...
    }
    

    alternatively you can fully qualify the name of the Item class you want to create:

    public void CountTestHelper() where Item : IHasRect
    {
        Rectangle rectangle = new Rectangle(0, 0, 100, 100); 
        SomeClass target = new SomeClass(rectangle);            
        Point p = new Point(10,10);
        SomeNamespace.Item i = new SomeNamespace.Item(p, 10);  
    }
    

提交回复
热议问题