【发布时间】:2016-04-15 20:23:25
【问题描述】:
背景
我有一个将 IQueryable 列表转换为 IEnumerable 的扩展方法:
public static IEnumerable<PersonDto> ToDtoList(
this IQueryable<Person> source)
{
var result = new List<PersonDto>();
foreach (var item in source)
{
result.Add(item.ToDto());
}
return result;
}
item.ToDto 扩展是这样做的:
public static PersonDto ToDto(this Person source)
{
if (source == null)
return null;
return new PersonDto
{
PersonId = source.personId,
Firstname = source.firstname,
Lastname = source.lastname,
DateOfBirth = source.dateOfBirth,
CreateDate = source.createDate,
ModifyDate = source.modifyDate,
};
}
问题
有没有办法配置以下内容以使item.ToDto() 工作?
public static IEnumerable<T2> ToDtoList<T, T2>(this IQueryable<T> source)
{
var result = new List<T2>();
foreach (var item in source)
{
result.Add(item.ToDto());
}
return result;
}
按原样,它不起作用,因为.ToDto 是item 的不可解析符号。
【问题讨论】:
-
您可以创建自定义界面,如
IToDto。然后从那里继承所有DTO类。并将约束添加到您的通用方法中作为` where T : IToDto` -
IToDtoInterface 是不是可以留空?
标签: c# .net web-applications asp.net-web-api