【发布时间】:2014-11-01 07:48:20
【问题描述】:
我有一个扩展方法:
public static List<object> ToModelViewObjectList<ModelViewType>(this IEnumerable<object> source)
{
List<ModelViewType> destinationList = new List<ModelViewType>();
PropertyInfo[] ModelViewProperties = typeof(ModelViewType).GetProperties();
foreach (var sourceElement in source)
{
object destElement = Activator.CreateInstance<ModelViewType>();
foreach (PropertyInfo sourceProperty in sourceElement.GetType().GetProperties())
{
if (ModelViewProperties.Select(m => m.Name).Contains(sourceProperty.Name))
{
destElement.GetType().GetProperty(sourceProperty.Name).SetValue(destElement, sourceProperty.GetValue(sourceElement));
}
}
destinationList.Add((ModelViewType)destElement);
}
return destinationList.Cast<object>().ToList();
}
我有一个对象列表的方法,我想在这个方法中调用扩展方法:
public void GridModel(IEnumerable<object> GridDataSource)
{
List<object> list = GridDataSource.ToModelViewObjectList<GridDataSource[0].GetType()>();
}
我应该写什么而不是 GridDataSource[0].GetType() ?
编辑:
我有一个带有对象参数的方法。我想创建一个对象类型的通用列表。
public void CreateListByNonGenericType(object myObject)
{
Type objType = myObject.GetType();
var lst = System.Collections.Generic.List < objType.MakeGenericType() > ();
}
我应该写什么而不是objType.MakeGenericType()?
【问题讨论】:
-
您需要编写一个在编译时已知的类型。
GridDataSource[0].GetType()只会在运行时知道。 -
那么,有没有办法做到这一点?
-
我能想到的唯一方法就是使用反射。
-
这里的泛型类型,是一个ModelView od MVC.Net,它将被填充和转换。然后作为对象列表将被发送到 View 进行渲染。
-
扩展方法从 IEnumerable
标签: c# generics extension-methods