繁体   English   中英

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

[英]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 有很多继承类,它们都有复制构造函数。

我收到:

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

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

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

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

谢谢。

要在泛型类型上使用new ,您必须在类/方法定义上指定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});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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