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

标签 c# generics type-constraints

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

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

我写了下面的方法:

 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,您必须在类/方法定义中指定 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});
}

关于c# - 具有新类型约束的通用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37570541/

相关文章:

c# - 通用参数基类型 : "There is no implicit reference conversion from B to A"

c# - 如何将 `where T : U` 泛型类型参数约束从 C# 转换为 F#?

generics - 如何表达函数的类型约束以允许添加不同类型的值?

c# - 代码隐藏页面不能 "see"在 aspx 页面中声明的任何项目/控件

c# - While Loop 不会一直循环

go - 如何为可以使用 len() 的东西编写 Go 类型约束?

java - 重写 "Java Effective"示例中泛型方法的绑定(bind)不匹配

c# - 使用 C# 获取以毫秒为单位的时间

c# - 查询数据表中行和列交叉处的特定值

c# - 如何定义继承泛型抽象类的泛型抽象类?