简体   繁体   English

如何获取动态类型的属性值?

[英]How get propery value of an dynamic type?

[update] [更新]

I'm sorry, i should tag this question as MVC-2, I pass result of query into view's model, so i must specify type of my model in View's header defintion.对不起,我应该将此问题标记为 MVC-2,我将查询结果传递给视图的 model,所以我必须在视图的 Z099FB995346F31C749F6E40DB0F35 定义中指定我的 model 的类型I declare it like this:我这样声明:

Inherits="System.Web.Mvc.ViewPage<IQueryable<dynamic>>"

how ever nothing changed and none of answers doesn't work for me:(. finally i used an ModelView class as helper to put my query result in it. :(怎么什么都没有改变,也没有一个答案对我不起作用:(。最后我使用 ModelView class 作为助手将我的查询结果放入其中。:(

[/update] [/更新]

I have a query like this:我有一个这样的查询:

IQueryable<dynamic> result = from d in KiaNetRepository.KiaNetEntities.Discounts
             where d.AgentTypeID == agentTypeId
             select new { d.Category,  d.DiscountValue, d.PriceConfige };

then i retrive value in my view like this:然后我在我的视图中检索价值,如下所示:

foreach(var item in result){

    Category cat = item.Category; // throws exception 'object' does not contain a definition for 'Category' 

    //...

}

note that type of query as IQueryable is anonymouse class...请注意,作为 IQueryable 的查询类型是匿名 class...

Try to declare names explicitly:尝试显式声明名称:

select new { Category = d.Category,  DiscountValue = d.DiscountValue, PriceConfige = d.PriceConfige }

If you are not forcing result to be of IQueryeable<dynamic> for any specific reason, I would recommend using var result =... .如果您出于任何特定原因不强制 result 为IQueryeable<dynamic> ,我建议使用var result =... This will let the compiler make result of type IQueryable<T> with T the type of the anonymous class that you create using new {... } in the select.这将使编译器生成类型为IQueryable<T>result ,其中T是您在 select 中使用new {... }创建的匿名 class 的类型。 There is no necessity for using dynamic from the code that you show here.没有必要从您在此处显示的代码中使用dynamic

If you replace the inappropriate declaration IQueryable<dynamic> by var , sure it works, I've just also tested it.如果您将不适当的声明IQueryable<dynamic>替换为var ,请确保它有效,我刚刚也对其进行了测试。

Your problem is that your foreach loop being in the view page gets compiled into a separate assembly.您的问题是视图页面中的foreach循环被编译为单独的程序集。 Since anonymous types are internal the dynamic doesn't see it because of the permissions don't allow it.由于匿名类型是内部的,因此动态不会看到它,因为权限不允许它。

Simplest fix is to call ToList() on your query statement and then select each anonymous type and copy parameters to a declared class or expandoobject.最简单的解决方法是在查询语句上调用ToList() ,然后调用 select 每个匿名类型并将参数复制到声明的 class 或 expandoobject。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM