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

后端 未结 3 1956
北恋
北恋 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:42

    You can't initialize Generic type object unless you mark it as implementing default constructor using new keyword:

    public void CountTestHelper() where Item : IHasRect, new()
     {
        Rectangle rectangle = new Rectangle(0, 0, 100, 100); 
        SomeClass target = new SomeClass(rectangle);            
        Point p = new Point(10,10);
        Item i = new Item();    // constructor has to be parameterless!
        ...
     }
    

    On the other hand, if you're trying to initialize an Item type object defined somewhere else in the application try using the namespace before it:

    MyAppNamespace.Item i = new MyAppNamespace.Item(p, 10);
    

提交回复
热议问题