具有新类型约束的泛型构造函数 [英] Generic constructor with new type constraint

查看:165
本文介绍了具有新类型约束的泛型构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have 2 types of objects, Database models and normal system models.

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

I want to be able to convery the model into Database model and vice versa.

我编写了以下方法:

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

基本上sysModeldbModel都是抽象的.

dbModel有很多继承类,这些继承类都具有复制构造函数.

dbModel have lots of inherting classes which all have copy constructors.

我正在接收:

无法创建类型参数为'E'的实例,因为它不会 具有new()约束

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

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

Im aware that technically sometimes I dont have a matching constructor for every value of T, at least that whats the debugger know.

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

I also tried adding the where E : dbModel, new() constraint, but its just irrelevant.

是否可以使用通用方法和参数将模型转换为另一个模型?

Is there a way to convert model into another model using generic method and using parameters?

谢谢.

推荐答案

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

To use new on a generic type, you would have to specify the new() constraint on your class/method definition:

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

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

Since you are using a parameter in the constructor, you can't use new, but you can use the Activator instead and pass other as an argument:

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

这篇关于具有新类型约束的泛型构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆