最近,我被要求用一句话来证明C# 3.0的力量(可能有点棘手)
我写了
new int[] { 1, 2, 3 }.Union(new int[]{10,23,45}).
ToList().ForEach(x => Console.WriteLine(x));并解释说你可以在一行中使用(i)匿名数组(ii)扩展方法(iii)lambda和闭包。
但是..。
面试官问我how will you convert an anonymous type into known type :(
我解释说
public class Product
{
public double ItemPrice { private set; get; }
public string ItemName { private set; get; }
}
var anony=new {ItemName="xxxx",ItemPrice=123.56};您不能分配product a=anony;
面试官回答说,如果你周围有一个小工作,那么有200%的机会这样做。我当时一无所知。
像往常一样,我在等待你的宝贵回复(可能吗?)。
发布于 2010-04-15 04:18:58
你说得对,你不能做这个任务:
product a=anony;MSDN:Anonymous Types (C# Programming Guide)
匿名类型不能强制转换为除object以外的任何接口或类型。
发布于 2010-04-15 04:35:15
可能是这样的:
class Program
{
static T Cast<T>(object target, T example)
{
return (T)target;
}
static object GetAnon()
{
return new { Id = 5 };
}
static void Main()
{
object anon = GetAnon();
var p = Cast(anon, new { Id = 0 });
Console.WriteLine(p.Id);
}
}备注:从不编写或依赖这样的代码。
发布于 2010-12-22 13:37:52
可能是尝试所示的示例here..they尝试做类似的事情。
http://www.codeproject.com/KB/linq/AnonymousTypeTransform.aspx
http://www.inflecto.co.uk/Inflecto-Blog/post/2009/11/12/IQueryable-Sorting-Paging-Searching-and-Counting.aspx
https://stackoverflow.com/questions/2640471
复制相似问题