Skip to main content
 首页 » 编程设计

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

2024年02月05日9leader

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

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

我写了下面的方法:

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

基本上 sysModel 和 dbModel 都是抽象的。

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

我收到了:

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

我知道从技术上讲,有时我没有为 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}); 
}