[英]Generic constructor with new type constraint
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.我希望能够将模型转换为数据库模型,反之亦然。
I have the following method I wrote:我有我写的以下方法:
public static E FromModel<T, E>(T other)
where T : sysModel
where E : dbModel
{
return new E(other);
}
basically both sysModel
and dbModel
are abstract.基本上
sysModel
和dbModel
都是抽象的。
dbModel have lots of inherting classes which all have copy constructors. dbModel 有很多继承类,它们都有复制构造函数。
Im receiving :我收到:
Cannot create an instance of type parameter 'E' becauase it does not have the new() constraint
无法创建类型参数“E”的实例,因为它没有 new() 约束
Im aware that technically sometimes I dont have a matching constructor for every value of T
, at least that whats the debugger know.我知道从技术上讲,有时我没有为
T
每个值提供匹配的构造函数,至少调试器知道这是什么。
I also tried adding the where E : dbModel, new()
constraint, but its just irrelevant.我还尝试添加
where E : dbModel, new()
约束,但它只是无关紧要。
Is there a way to convert model into another model using generic method and using parameters?有没有办法使用泛型方法和使用参数将模型转换为另一个模型?
Thanks.谢谢。
To use new
on a generic type, you would have to specify the new()
constraint on your class/method definition:要在泛型类型上使用
new
,您必须在类/方法定义上指定new()
约束:
public static E FromModel<T, E>(T other)
where T : sysModel
where E : dbModel, new()
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:由于您在构造函数中使用参数,因此不能使用
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.