大家好, 假设
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 ?
更多推荐
获取匿名列表的类型
发布评论