获取匿名列表的类型

编程入门 行业动态 更新时间:2024-10-15 18:29:10
本文介绍了获取匿名列表的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

大家好, 假设

Hi all, let suppose

var res = result.Select(s=> new {id=s.id,name=s.name}).ToList();

现在,我想通过诸如func(res)之类的其他方法来传递此res. 请告诉我如何获取此资源的类型或如何从资源中获取数据.

now i want pass this res in another method like func(res). Please tell me that how can i get the type of this res or how i can get data from res.

推荐答案

您将无法执行匿名操作类作为变量,因为它仅在此范围的上下文中使用且有效.您将需要创建一个具体的类或结构. You won''t be able to pas the anonymous class as a variable since it is only used and valid with the context of this scope. You will need to create a concrete class or struct.

嗯,在.NET 4中使用新的"dynamic"关键字可以做到这一点. :但是,无论您是否应该这样做,都需要仔细评估. 考虑: Well, there is a "back-door" way to do this, using the new ''dynamic'' keyword in .NET 4: but whether you should do this, or not, you need to carefully evaluate. Consider: List<int> newList = new List<int> {1, 2, 3}; // you could also use .ToList<int>() here var result = newList.Select(itm => itm).ToList(); UseListMadeUsingVar(result);

,函数''UseListMadeUsingVar是:

And the function ''UseListMadeUsingVar is:

private void UseListMadeByVar(dynamic aList) { Type type = aList.GetType(); bool isListInt = aList is List<int>; }

通过将输入参数声明为动态",可以从本质上避免编译时类型检查. 建议您运行上面的代码,在设置了布尔变量"isListInt"之后放置一个断点,并检查"type"和"isListInt"的值以验证您是否获得了List< int>.传入. 然后,您需要考虑如何处理以这种方式传递的后期绑定结果:使用前是否需要进行类型检查?

By declaring the input parameter as ''dynamic'' you essentially avoid compile-time type checking. Suggest you run the above code, put a break-point after the boolean variable ''isListInt is set, and examine the values of both ''type and ''isListInt to verify that you are getting a List<int> passed in. And then, you need to think about what you might need to do with a late-bound result passed in this way: do you need to type-check before using ?

更多推荐

获取匿名列表的类型

本文发布于:2023-11-07 00:40:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565083.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!