Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

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

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() constraint

Required information for below:

public interface IHasRect
{
    Rectangle Rectangle { get; }
}

Helper class:

class Item : IHasRect
{
    public Item(Point p, int size)
    {
        m_size = size;
        m_rectangle = new Rectangle(p.X, p.Y, m_size, m_size); 
    }
}

For the function to be tested, I need to instantiate an object...

public class SomeClass<T> where T : IHasRect

The test:

public void CountTestHelper<Item>() where Item : IHasRect
{
    Rectangle rectangle = new Rectangle(0, 0, 100, 100); 
    SomeClass<Item> target = new SomeClass<Item>(rectangle);            
    Point p = new Point(10,10);
    Item i = new Item(p, 10);      // error here        
    ...
}
[TestMethod()]
public void CountTest()
{
    CountTestHelper<Item>();
}   

I am trying to understand what this error means, or how to fix it, by reading http://msdn.microsoft.com/en-us/library/d5x73970.aspx and http://msdn.microsoft.com/en-us/library/x3y47hd4.aspx - but it doesn't help.

I don't understand this error - I have already constrained the "SomeClass" to be of type. I cannot constrain the entire Test class (the unit test class generated by Visual Studio, which contains all the tests) - I will get a number of other errors otherwise. The Item class doesn't have any template...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

public void CountTestHelper<Item>() where Item : IHasRect, new()
 {
    Rectangle rectangle = new Rectangle(0, 0, 100, 100); 
    SomeClass<Item> target = new SomeClass<Item>(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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...