[英]How to make Generic method in C#
I have a lot of methods like these in a serviceContract I'm making: 我在serviceContract中有很多这样的方法:
TemplateContract CreateTemplateContract(Template t)
{
return new TemplateContract()
{
Id = t.Id,
Name = t.Name,
Description = t.Description,
DataLayoutId = t.DataLayoutId,
FieldLayoutId = t.FieldLayoutId,
SheetId = t.SheetId,
ThemeId = t.ThemeId
};
}
Template CreateTemplate(TemplateContract t)
{
return new Template()
{
Id = t.Id,
Name = t.Name,
Description = t.Description,
DataLayoutId = t.DataLayoutId,
FieldLayoutId = t.FieldLayoutId,
SheetId = t.SheetId,
ThemeId = t.ThemeId
};
}
These are methods to translate POCO's to DTO's and the other way around, I was wondering if I could some of these generic, it would be a lot cleaner, but I haven't got a lot of experience in generic Coding and couldn't quiet figure it out yet 这些是将POCO转换为DTO的方法,反之亦然,我想知道是否可以使用其中的一些通用代码,这样会更清洁,但是我在通用编码方面没有很多经验,也无法安静弄清楚了
You maybe better off looking at AutoMapper which can do a lot of this mapping automatically for you 您可能最好看看AutoMapper ,它可以自动为您完成很多映射
if you really want to use generics unless they share a base class it's not possible, if they do you need to us a generic constraint on the base class and on a parameter less constructor so your method signature would be like 如果您真的想使用泛型,除非它们共享一个基类,那是不可能的,如果它们确实需要,我们需要对基类和不带参数的构造函数的泛型约束,那么您的方法签名就像
public TemplateBase Map< TemplateBase>(TemplateBase request) where TemplateBase : new
{
return new TemplateBase()
{
....
}
}
Did you try AutoMapper that map in a very easy way? 您是否以一种非常简单的方式尝试了AutoMapper映射?
If you don't want to use this library, you can at least watch the code to have inspiration. 如果您不想使用此库,则至少可以观看代码以获取灵感。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.