通用函数和新约束

Generic function and new constraint

我如何使用两个参数,一个继承自 IProject,另一个具有 new() 约束?以下未通过编译并出现 "Cannot create an instance of the variable type 'T' because it does not have the new() constraint" 错误。

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

如果你想对多个参数应用约束,那么你需要添加第二个where作为:

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

此外,您还需要 return 从您的方法中得到一些东西:

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

P.S:为了应用new约束,类型参数必须有一个public无参数构造函数。

阅读 This 了解更多信息。