具有新类型约束的泛型构造函数

Ori*_*ael 3 c# generics type-constraints

我有两种类型的对象,数据库模型和普通系统模型。

我希望能够将模型转换为数据库模型,反之亦然。

我有我写的以下方法:

 public static E FromModel<T, E>(T other) 
            where T : sysModel
            where E : dbModel
{
     return new E(other);
}
Run Code Online (Sandbox Code Playgroud)

基本上都sysModeldbModel都是抽象的。

dbModel 有很多继承类,它们都有复制构造函数。

我收到:

无法创建类型参数“E”的实例,因为它没有 new() 约束

我知道从技术上讲,有时我没有为 的每个值提供匹配的构造函数T,至少调试器知道这是什么。

我也尝试添加where E : dbModel, new()约束,但它只是无关紧要。

有没有办法使用泛型方法和使用参数将模型转换为另一个模型?

谢谢。

Man*_*mer 5

new在泛型类型上使用,您必须new()在类/方法定义上指定约束:

public static E FromModel<T, E>(T other) 
        where T : sysModel
        where E : dbModel, new()
Run Code Online (Sandbox Code Playgroud)

由于您在构造函数中使用参数,因此不能使用new,但可以使用Activator代替并other作为参数传递:

public static E FromModel<T, E>(T other)
    where T : sysModel
    where E : dbModel
{
    return (E)Activator.CreateInstance(typeof(E), new[]{other});
}
Run Code Online (Sandbox Code Playgroud)