Convert generic type to another generic type extension method
I am doing something illegal here as the compiler complains but I do not know what I should do instead. Basically I want to convert a list of one type to a list of another type. Any help much appreciated. Here is my extension method:
public static List<TTypeConvertTo> ConvertFromEntityContext<TTypeConvertFrom>(this List<TTypeConvertFrom> source)
where TTypeConvertTo : BaseModel
{
List<TTypeConvertTo> result = null;
if (source != null)
{
result = new List<TTypeConvertTo>();
foreach (var item in source)
{
result.Add(item.ConvertFromEntityContex开发者_StackOverflow中文版t());
}
}
return result;
}
If the method is generic, it should include all generic types, including TTypeConvertTo
. You probably don't need TTypeConvertFrom
as a generic type, so try:
public static List<TTypeConvertTo> ConvertFromEntityContext<TTypeConvertTo>
(this List<FromBaseModel> source)
If you need both types to be generic (which doesn't really seem necessary), you also have to have TTypeConvertFrom
constrained to a base type that has the method ConvertFromEntityContext
:
public static List<TTypeConvertTo> ConvertFromEntityContext<TTypeConvertFrom, TTypeConvertTo>
(this List<TTypeConvertFrom > source)
where TTypeConvertTo : BaseModel, TTypeConvertFrom : FromBaseModel
That is less advisable, as it will make the call overly verbose: the compiler cannot infer the return type, so you'll have to specify both types every time you call the method.
Either way, you can use LINQ to rewrite the body of your method:
if (source == null)
return null;
return source.Select(item => item.ConvertFromEntityContext()).ToList();
精彩评论