动态/匿名类型,返回匿名类型!
这不是一个问题,因为我认为它的讨论,我知道你不能跨方法返回匿名类型,当我第一次使用匿名类型时,我认为能够跨方法返回它真的很好,当 .net 4 出来时有了动态类型的版本,我认为可能有希望通过这样的动态类型返回匿名类型:
public static dynamic getCustomer()
{
.....
var x = from c in customers
select new {Fname = c.FirstName};
return x;
}
然后,
static void Main(string[] args)
{
dynamic x = getCustomer();
Console.WriteLine(x.First().Fname);
Console.ReadKey();
}
但遗憾的是,尽管它编译得很好,但它不起作用,
我猜原因是:
编译中已知的匿名类型类型并且必须包装到运行时已知的类中!现在,匿名类型在编译时携带其信息,希望某个类能够将这些信息传递到运行时,但动态类型在编译时是未知的,因此通过动态传递匿名类型类型强制匿名类型丢失其信息/智能,我尝试调试,我可以获得我想要的数据,但我想它只能在调试模式下工作,或者我可能错过了一些东西。
我想知道是否有人让它发挥作用或考虑过它?
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 really 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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以返回匿名类型,只是不能声明您会这样做。您可以使用 可怕的黑客。
您的代码不起作用的原因与匿名类型无关 - 它与动态类型中找不到扩展方法有关。
更改为:
我希望它会起作用。
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:
and I expect it will work.