C# - 访问问题匿名类型

时间:2010-04-14 19:39:57

标签: c#-3.0 language-features

最近我被要求在一行中证明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%的机会这样做 如果你有一个小工作。我是无能为力。

像往常一样,我在等待您的宝贵回复(是否可能?)。

4 个答案:

答案 0 :(得分:1)

你说得对,你不能做这个任务:

product a=anony;

MSDN:Anonymous Types (C# Programming Guide)

  

无法转换为匿名类型   任何接口或类型除外   对象

答案 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)

答案 3 :(得分:0)

var list = anony.Select(x=> new Product {
               ItemPrice = x.ItemPrice, ItemName = x.ItemName }).ToList();