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

Categories

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

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

1 Answer

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)
{
    // ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...