最近我被要求在一行中证明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%的机会这样做 如果你有一个小工作。我是无能为力。
像往常一样,我在等待您的宝贵回复(是否可能?)。
答案 0 :(得分:1)
答案 1 :(得分:0)
也许是这样的:
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);
}
}
备注:从不写或依赖此类代码。
答案 2 :(得分:0)
可以尝试这里显示的例子......他们尝试做类似的事情......
http://www.codeproject.com/KB/linq/AnonymousTypeTransform.aspx
答案 3 :(得分:0)
var list = anony.Select(x=> new Product {
ItemPrice = x.ItemPrice, ItemName = x.ItemName }).ToList();