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
212 views
in Technique[技术] by (71.8m points)

c# - Create a new instance of T without the new constraint

If one wants to create a new instance of a generic, the new constraint needs to be defined, like so:

public T SomeMethod<T>() where T : new()
{
    return new T();
}

Is it possible, using reflection, to create an instance of T without the new constraint, like so (contains pseudocode):

public T SomeMethod<T>()
{
    if (T has a default constructor)
    {
        return a new instance of T;
    }
    else
    {
        return Factory<T>.CreateNew();
    }
}
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use Activator.CreateInstance() for this. See http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx for more information on how to use this method. Basically, what you do is:

var obj = (T)Activator.CreateInstance(typeof(T));

You can verify whether it has a default constructor by using the GetConstructors() method:

var constructors = typeof(T).GetConstructors();

If you find a constructor that has zero parameters, you can use the Activator.CreateInstance method. Otherwise, you use the Factory<T>.CreateNew() method.

EDIT:

To find out directly whether a constructor without any parameters exist, you can use the following check:

if (typeof(T).GetConstructor(Type.EmptyTypes) != null)
{
    // ...

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

...