简体   繁体   中英

Generic function and new constraint

How can I use two parameters while one inherits from IProject and other has a new() constraint? The following doesn't pass compilation with the "Cannot create an instance of the variable type 'T' because it does not have the new() constraint" error.

public static T CreateNewProject<T, V>(string token, string projectName) where V : IProject<T>, T new()
{
    T project = new T(); 
}

If you want to apply constraints to multiple parameters, then you need to add second where as:

where V : IProject<T> 
where T : new()

And also, you need to return something from your method:

public static T CreateNewProject<T, V>(string token, string projectName) 
    where V : IProject<T> 
    where T : new()
{
    return new T();
}

PS: For applying new constraint, the type argument must have a public parameterless constructor.

Read This for more information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM