转换匿名类型来
问题描述:
类
我有一个列表anBook内部的匿名类型:转换匿名类型来
var anBook=new []{
new {Code=10, Book ="Harry Potter"},
new {Code=11, Book="James Bond"}
};
是尽可能将其与clearBook的如下定义转换到一个列表:使用
public class ClearBook
{
int Code;
string Book;
}
直接转换,即没有循环通过一本书?
答
嗯,你可以使用:
var list = anBook.Select(x => new ClearBook {
Code = x.Code, Book = x.Book}).ToList();
但没有,没有直接的转换支持。显然,你需要添加访问器等。(不要使公共领域) - 我猜:
public int Code { get; set; }
public string Book { get; set; }
当然,另一种选择是开始与你想要的数据:
var list = new List<ClearBook> {
new ClearBook { Code=10, Book="Harry Potter" },
new ClearBook { Code=11, Book="James Bond" }
};
也有事情可以做与反射映射数据(可能使用一个Expression
编译和缓存策略),但它可能是不值得的。
答
正如马克所说,它可以通过反射和表达树来完成...并且幸运的是,MiscUtil中有一个类就是这样做的。但是,更仔细地看看你的问题,听起来像你想要将这个转换应用到一个集合(数组,列表或其他)而没有循环。这不可能工作。您正在从一种类型转换为另一种类型 - 它不像您可以使用对匿名类型的引用,就好像它是对ClearBook的引用。
举的PropertyCopy类的工作虽然一个例子,你只需要:
var books = anBook.Select(book => PropertyCopy<ClearBook>.CopyFrom(book))
.ToList();
答
什么有关这些扩展?简单地调用您的匿名类型的.ToNonAnonymousList ..
public static object ToNonAnonymousList<T>(this List<T> list, Type t)
{
//define system Type representing List of objects of T type:
Type genericType = typeof (List<>).MakeGenericType(t);
//create an object instance of defined type:
object l = Activator.CreateInstance(genericType);
//get method Add from from the list:
MethodInfo addMethod = l.GetType().GetMethod("Add");
//loop through the calling list:
foreach (T item in list)
{
//convert each object of the list into T object by calling extension ToType<T>()
//Add this object to newly created list:
addMethod.Invoke(l, new[] {item.ToType(t)});
}
//return List of T objects:
return l;
}
public static object ToType<T>(this object obj, T type)
{
//create instance of T type object:
object tmp = Activator.CreateInstance(Type.GetType(type.ToString()));
//loop through the properties of the object you want to covert:
foreach (PropertyInfo pi in obj.GetType().GetProperties())
{
try
{
//get the value of property and try to assign it to the property of T type object:
tmp.GetType().GetProperty(pi.Name).SetValue(tmp, pi.GetValue(obj, null), null);
}
catch (Exception ex)
{
Logging.Log.Error(ex);
}
}
//return the T type object:
return tmp;
}
不能CLR推断类型和属性名称并执行自动转换吗? .Net 4.0应该改进这个 – Graviton 2009-01-15 09:03:04