开发者

Dynamic/Anonymous type, returning anonymous types!

this is not a question as i think its discussion, i know you cant return an anonymous type across methods, when i first used anonymous types i thought it would be r开发者_Go百科eally nice to be able to return it across methods and when .net 4 came out and with the edition of the dynamic types i thought there might be a hope in returning an anonymous type through dynamic type like this:

      public static dynamic  getCustomer()
    {
        .....
        var x = from c in customers
                select new {Fname = c.FirstName};

        return x;
    }

and then

static void Main(string[] args)
    {
        dynamic x = getCustomer();
        Console.WriteLine(x.First().Fname);
        Console.ReadKey();
    }

but sadly that doesnt work although it compile good,

i guess the reason why is :

Anonymous types known in compile type and must be wrapped into classes that is KNOWN IN RUNTIME !, now anonymous type carry thier information in the compile time hoping some class will come and take this information to runtime , but dynamic type are unkown in compile time so passing anonymous type through dynamic type force the anonymous type to loss its informations/intellisence, i tried to debug and i could get the data i wanted but i guess it works only in debug mode , or maybe im missing something.

i was wondering if any one got it to work or thought about it ?


You can return an anonymous type, you just can't declare that you'll do so. You can get round it with a horrible hack.

The reason your code doesn't work is nothing to do with anonymous types - it's to do with extension methods not being found in dynamic typing.

Change to:

Console.WriteLine(Enumerable.First(x).Fname);

and I expect it will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜