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

Generic constructor with new type constraint

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

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

我写的方法如下:

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

基本上sysModeldbModel都是抽象的

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

我收到了:

Cannot create an instance of type parameter 'E' becauase it does not have the new() constraint

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

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

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

谢谢。

要在通用类型上使用 new,您必须在 class/method 定义中指定 new() 约束:

public static E FromModel<T, E>(T other) 
        where T : sysModel
        where E : dbModel, new()

由于您在构造函数中使用参数,因此不能使用 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});
}