Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

regarding the use of new Constraint in c#

i never use new Constraint because the use is not clear to me. here i found one sample but i just do not understand the use. here is the code

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

public class ItemFactory2<T> where T : IComparable, new()

{
}

so anyone please make me understand the use of new Constraint with small & easy sample for real world use. thanks

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

This constraint requires that the generic type that is used is non-abstract and that it has a default (parameterless) constructor allowing you to call it.

Working example:

class ItemFactory<T> where T : new()
{
    public T GetNewItem()
    {
        return new T();
    }
}

which obviously now will force you to have a parameterless constructor for the type that is passed as generic argument:

var factory1 = new ItemFactory<Guid>(); // OK
var factory2 = new ItemFactory<FileInfo>(); // doesn't compile because FileInfo doesn't have a default constructor
var factory3 = new ItemFactory<Stream>(); // doesn't compile because Stream is an abstract class

Non-working example:

class ItemFactory<T>
{
    public T GetNewItem()
    {
        return new T(); // error here => you cannot call the constructor because you don't know if T possess such constructor
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...