【发布时间】:2011-11-22 11:48:20
【问题描述】:
我为 IQueryable 类创建了一个扩展方法,将通用源类的列表转换为其他通用目标类的列表,(.net3.5)
我正在使用反射从源对象值中获取属性并将其分配给目标对象。
该类的源码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;
namespace System.Linq
{
public static class QueryableExtensions
{
public static IQueryable<TDest> ToDTO<TDest>(this IQueryable<TSource> source)//getting error on this line
{
return DTOTranslator<TDest>.ConvertToDTO<TDest>(source);
}
}
public class DTOTranslator<TSource>
{
public static IQueryable<TDest> ConvertToDTO<TDest>(IQueryable<TSource> source)
{
List<TDest> destinationList = new List<TDest>();
List<TSource> sourceList = source.ToList<TSource>();
var sourceType = typeof(TSource);
var destType = typeof(TDest);
foreach (TSource sourceElement in sourceList)
{
TDest destElement = Activator.CreateInstance<TDest>();
//Get all properties from the object
PropertyInfo[] sourceProperties = typeof(TSource).GetProperties();
foreach (PropertyInfo sourceProperty in sourceProperties)
{
//and assign value to each propery according to property name.
PropertyInfo destProperty = destType.GetProperty(sourceProperty.Name);
destProperty.SetValue(destElement, sourceProperty.GetValue(sourceElement, null), null);
destinationList.Add(destElement);
}
}
return destinationList.AsQueryable();
}
}
}
但是在编译时我在第 12 行收到错误:
The type or namespace name 'TSource' could not be found (are you missing a using directive or an assembly reference?)
更新:
感谢大家的回复。
现在我已将我的课程更新如下:
public static class QueryableExtensions
{
public static IQueryable<TDest> ToDTO<TSource, TDest>(this IQueryable<TSource> source)
{
List<TDest> destinationList = new List<TDest>();
List<TSource> sourceList = source.ToList<TSource>();
var sourceType = typeof(TSource);
var destType = typeof(TDest);
foreach (TSource sourceElement in sourceList)
{
TDest destElement = Activator.CreateInstance<TDest>();
//Get all properties from the object
PropertyInfo[] sourceProperties = typeof(TSource).GetProperties();
foreach (PropertyInfo sourceProperty in sourceProperties)
{
//and assign value to each propery according to property name.
PropertyInfo destProperty = destType.GetProperty(sourceProperty.Name);
destProperty.SetValue(destElement, sourceProperty.GetValue(sourceElement, null), null);
destinationList.Add(destElement);
}
}
return destinationList.AsQueryable();
}
}
这很好用,
现在我唯一想知道的是-
是否可以跳过<TSource> 参数,
如何从 IQueryable 的元素类型中读取它并定义它的对象?
我的意思是目前我将该方法称为
IQueryable<CATEGORY_DTO> dtos = (from p in new MyEntities().CATEGORY select p).ToDTO<CATEGORY, CATEGORY_DTO>();
我想称之为
IQueryable<CATEGORY_DTO> dtos = (from p in new MyEntities().CATEGORY select p).ToDTO<CATEGORY_DTO>();
谢谢,新泽西
【问题讨论】:
标签: c# .net asp.net-3.5